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

extensions.mddocs/

Extension System

MathJax uses a modular component system that allows loading input processors, output processors, and specialized extensions on demand. This provides flexibility in customizing functionality while keeping bundle sizes optimized.

Capabilities

Component Loading

Load MathJax components dynamically based on requirements.

/**
 * Load specified components
 * @param components - List of component names to load
 * @returns Promise that resolves when all components are loaded
 */
function load(...components: string[]): Promise<any[]>;

/**
 * Mark components as pre-loaded
 * @param components - List of component names to mark as loaded
 */
function preLoaded(...components: string[]): void;

/**
 * Check component version compatibility
 * @param component - Component name
 * @param version - Required version
 * @param name - Component display name
 * @returns Whether version is compatible
 */
function checkVersion(component: string, version: string, name: string): boolean;

/**
 * Get root path for component loading
 * @returns Root path string
 */
function getRoot(): string;

Usage Examples:

// Load individual components
await MathJax.loader.load('input/tex', 'output/svg');

// Load multiple components
await MathJax.loader.load(
  'input/tex',
  '[tex]/ams',
  '[tex]/color',
  'output/chtml',
  'a11y/semantic-enrich'
);

// Mark components as pre-loaded (for bundled components)
MathJax.loader.preLoaded('startup', 'core');

// Check version compatibility
const isCompatible = MathJax.loader.checkVersion('input/tex', '4.0.0', 'TeX Input');

// Get component root path
const rootPath = MathJax.loader.getRoot();

Extension Configuration

Configure which components to load through the loader configuration.

interface LoaderOptions {
  /** Components to load automatically */
  load?: string[];
  /** Component dependencies */
  dependencies?: Record<string, string[]>;
  /** Path mappings for component loading */
  paths?: Record<string, string>;
  /** Source file mappings */
  source?: Record<string, string>;
  /** Components provided by other components */
  provides?: Record<string, string[]>;
}

Configuration Examples:

// Basic component loading
MathJax.config.loader = {
  load: ['input/tex', '[tex]/ams', 'output/chtml']
};

// Advanced configuration with custom paths
MathJax.config.loader = {
  load: ['input/tex', 'output/svg', 'ui/menu'],
  paths: {
    mathjax: 'https://cdn.jsdelivr.net/npm/mathjax@4',
    custom: 'https://my-cdn.com/mathjax-extensions'
  },
  dependencies: {
    'custom/myextension': ['input/tex']
  }
};

Available Components

Input Components

Process different mathematical notation formats.

Core Input Processors:

  • input/tex - Complete TeX/LaTeX processor with extensions
  • input/tex-base - Basic TeX processor without extensions
  • input/mml - MathML processor
  • input/asciimath - AsciiMath processor

Usage Examples:

// Load TeX with extensions
MathJax.config.loader.load = ['input/tex'];

// Load basic TeX only  
MathJax.config.loader.load = ['input/tex-base'];

// Load multiple input formats
MathJax.config.loader.load = ['input/tex', 'input/mml', 'input/asciimath'];

Output Components

Render mathematics in different formats.

Available Output Processors:

  • output/chtml - CommonHTML output (HTML/CSS)
  • output/svg - SVG output (Scalable Vector Graphics)

Usage Examples:

// Use CommonHTML output
MathJax.config.loader.load = ['input/tex', 'output/chtml'];

// Use SVG output
MathJax.config.loader.load = ['input/tex', 'output/svg'];

// Both outputs available (choose at conversion time)
MathJax.config.loader.load = ['input/tex', 'output/chtml', 'output/svg'];

TeX Extensions

Extend TeX/LaTeX functionality with specialized packages.

Core Extensions:

  • [tex]/ams - AMS math environments and symbols
  • [tex]/amscd - AMS commutative diagrams
  • [tex]/newcommand - Define custom commands
  • [tex]/color - Color support

Mathematical Extensions:

  • [tex]/boldsymbol - Bold mathematical symbols
  • [tex]/braket - Dirac bra-ket notation
  • [tex]/cancel - Cancel expressions with lines
  • [tex]/enclose - Enclose expressions with boxes/lines
  • [tex]/mhchem - Chemistry notation
  • [tex]/physics - Physics notation and operators
  • [tex]/units - Unit formatting

Formatting Extensions:

  • [tex]/bbox - Bounding boxes and backgrounds
  • [tex]/textmacros - Text formatting commands
  • [tex]/unicode - Unicode character support
  • [tex]/verb - Verbatim text rendering

Advanced Extensions:

  • [tex]/autoload - Automatic extension loading
  • [tex]/require - Dynamic requirement loading
  • [tex]/configmacros - Configuration-based macros

Usage Examples:

// Load specific extensions
MathJax.config.loader.load = [
  'input/tex',
  '[tex]/ams',
  '[tex]/color',
  '[tex]/mhchem',
  'output/chtml'
];

// Load many extensions
MathJax.config.loader.load = [
  'input/tex',
  '[tex]/ams',
  '[tex]/amscd', 
  '[tex]/bbox',
  '[tex]/boldsymbol',
  '[tex]/braket',
  '[tex]/cancel',
  '[tex]/color',
  '[tex]/enclose',
  '[tex]/mhchem',
  '[tex]/physics',
  'output/svg'
];

Accessibility Components

Enhance mathematical accessibility for assistive technologies.

Available Components:

  • a11y/semantic-enrich - Semantic analysis and enrichment
  • a11y/speech - Speech generation
  • a11y/explorer - Interactive exploration
  • a11y/complexity - Mathematical complexity analysis
  • a11y/assistive-mml - Assistive MathML generation
  • a11y/sre - Speech Rule Engine

Usage Examples:

// Full accessibility support
MathJax.config.loader.load = [
  'input/tex',
  'output/chtml',
  'a11y/semantic-enrich',
  'a11y/speech',
  'a11y/explorer',
  'a11y/assistive-mml'
];

// Basic accessibility
MathJax.config.loader.load = [
  'input/tex',
  'output/svg', 
  'a11y/assistive-mml'
];

UI Components

User interface elements and interactions.

Available Components:

  • ui/menu - Context menu for mathematical expressions
  • ui/lazy - Lazy loading utilities
  • ui/safe - Safe mode error handling

Usage Examples:

// Add context menu
MathJax.config.loader.load = [
  'input/tex',
  'output/chtml',
  'ui/menu'
];

// Safe mode with error handling
MathJax.config.loader.load = [
  'input/tex',
  'output/svg',
  'ui/safe'
];

Adaptor Components

DOM adapters for different environments.

Available Adaptors:

  • adaptors/liteDOM - Lightweight DOM for server-side
  • adaptors/jsdom - jsdom integration
  • adaptors/linkedom - LinkedOM integration

Usage Examples:

// Node.js with liteDOM
MathJax.config.loader.load = [
  'adaptors/liteDOM',
  'input/tex',
  'output/svg'
];

// Node.js with jsdom
MathJax.config.loader.load = [
  'adaptors/jsdom', 
  'input/tex',
  'output/chtml'
];

Pre-built Component Combinations

Single Input/Output Combinations

Ready-to-use combinations for common scenarios.

Available Combinations:

  • tex-chtml.js - TeX input + CommonHTML output
  • tex-svg.js - TeX input + SVG output
  • mml-chtml.js - MathML input + CommonHTML output
  • mml-svg.js - MathML input + SVG output

No-Font Variants:

  • tex-chtml-nofont.js - TeX + CommonHTML without web fonts
  • tex-svg-nofont.js - TeX + SVG without web fonts
  • mml-chtml-nofont.js - MathML + CommonHTML without fonts
  • mml-svg-nofont.js - MathML + SVG without fonts

Multi-Input Combinations

Support multiple input formats simultaneously.

Available Combinations:

  • tex-mml-chtml.js - TeX + MathML inputs + CommonHTML output
  • tex-mml-svg.js - TeX + MathML inputs + SVG output

Usage Examples:

<!-- Single format -->
<script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-chtml.js"></script>

<!-- Multiple formats -->
<script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-mml-svg.js"></script>

<!-- Without fonts -->
<script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-svg-nofont.js"></script>

Custom Extensions

Creating Custom Extensions

Build custom extensions for specialized mathematical notation.

// Define custom extension
const MyCustomExtension = {
  name: 'custom',
  version: '1.0.0',
  
  // Extension initialization
  init(config) {
    console.log('Custom extension loaded');
  },
  
  // Add custom macros
  macros: {
    customSymbol: '{\\unicode{x1D4C0}}',
    myFunction: ['{\\operatorname{#1}}', 1]
  },
  
  // Add custom environments
  environments: {
    myenvironment: ['\\begin{array}{cc}', '\\end{array}']
  }
};

// Register custom extension
MathJax.config.tex = MathJax.config.tex || {};
MathJax.config.tex.packages = MathJax.config.tex.packages || [];
MathJax.config.tex.packages.push('custom');

// Load the extension
MathJax.config.loader.source['[tex]/custom'] = 'path/to/my-extension.js';
MathJax.config.loader.load.push('[tex]/custom');

Custom Input Processors

Create input processors for new mathematical formats.

// Custom input processor template
class CustomInputJax {
  constructor(config = {}) {
    this.config = config;
  }
  
  // Process input string
  compile(math, doc) {
    // Parse custom format
    const parsed = this.parse(math.math);
    
    // Convert to internal format
    return this.convertToInternal(parsed);
  }
  
  parse(input) {
    // Custom parsing logic
    return { type: 'custom', content: input };
  }
  
  convertToInternal(parsed) {
    // Convert to MathJax internal format
    return this.createMathML(parsed);
  }
  
  createMathML(parsed) {
    // Generate MathML representation
    return '<math><mi>' + parsed.content + '</mi></math>';
  }
}

// Register custom input processor
MathJax.startup.registerConstructor('customInput', CustomInputJax);
MathJax.startup.useInput('customInput');

Custom Output Processors

Create output processors for new rendering formats.

// Custom output processor template
class CustomOutputJax {
  constructor(config = {}) {
    this.config = config;
  }
  
  // Render mathematics
  typeset(math, html) {
    const mathML = math.root;
    const customHTML = this.renderCustom(mathML);
    
    math.typesetRoot = html.node('span', {
      class: 'mjx-custom'
    }, [customHTML]);
    
    return math.typesetRoot;
  }
  
  renderCustom(mathml) {
    // Custom rendering logic
    return this.createCustomElement(mathml);
  }
  
  createCustomElement(mathml) {
    // Generate custom HTML structure
    return '<span class="custom-math">' + mathml.textContent + '</span>';
  }
  
  styleSheet() {
    // Return custom CSS
    return `
      .mjx-custom {
        font-family: 'Custom Math Font';
        color: #333;
      }
      .custom-math {
        border: 1px solid #ddd;
        padding: 2px 4px;
      }
    `;
  }
}

// Register custom output processor
MathJax.startup.registerConstructor('customOutput', CustomOutputJax);
MathJax.startup.useOutput('customOutput');

Dynamic Extension Loading

Runtime Extension Loading

Load extensions dynamically based on content or user preferences.

// Analyze content to determine needed extensions
function analyzeContent(content) {
  const extensions = [];
  
  if (content.includes('\\ce{')) {
    extensions.push('[tex]/mhchem');
  }
  
  if (content.includes('\\color{')) {
    extensions.push('[tex]/color');
  }
  
  if (content.includes('\\cancel{')) {
    extensions.push('[tex]/cancel');
  }
  
  if (content.includes('\\bra{') || content.includes('\\ket{')) {
    extensions.push('[tex]/braket');
  }
  
  return extensions;
}

// Load extensions dynamically
async function processContentWithExtensions(content) {
  const needed = analyzeContent(content);
  
  if (needed.length > 0) {
    await MathJax.loader.load(...needed);
  }
  
  // Process content
  return MathJax.tex2svg(content);
}

// Usage
const chemistry = '\\ce{H2O + CO2 -> H2CO3}';
const result = await processContentWithExtensions(chemistry);

Conditional Extension Loading

Load extensions based on environment or user capabilities.

// Environment-based loading
function loadEnvironmentExtensions() {
  const extensions = ['input/tex', 'output/chtml'];
  
  // Add accessibility if screen reader detected
  if (hasScreenReader()) {
    extensions.push('a11y/semantic-enrich', 'a11y/speech');
  }
  
  // Add menu for desktop browsers
  if (isDesktop()) {
    extensions.push('ui/menu');
  }
  
  // Add specific adaptors for Node.js
  if (typeof window === 'undefined') {
    extensions.push('adaptors/liteDOM');
  }
  
  return MathJax.loader.load(...extensions);
}

function hasScreenReader() {
  return navigator.userAgent.includes('NVDA') ||
         navigator.userAgent.includes('JAWS') ||
         window.speechSynthesis;
}

function isDesktop() {
  return !('ontouchstart' in window);
}

// Load appropriate extensions
loadEnvironmentExtensions().then(() => {
  MathJax.typeset();
});

Extension Dependencies

Dependency Management

MathJax automatically manages extension dependencies.

// Dependencies are defined in the loader configuration
MathJax.config.loader.dependencies = {
  // AMS package requires newcommand
  '[tex]/ams': ['input/tex-base', '[tex]/newcommand'],
  
  // Physics requires AMS
  '[tex]/physics': ['input/tex-base', '[tex]/ams'],
  
  // Color extensions
  '[tex]/colortbl': ['input/tex-base', '[tex]/color'],
  
  // Accessibility dependencies
  'a11y/speech': ['a11y/semantic-enrich'],
  'a11y/explorer': ['a11y/speech']
};

// When you load an extension, dependencies are loaded automatically
await MathJax.loader.load('[tex]/physics');
// This automatically loads: input/tex-base, [tex]/newcommand, [tex]/ams

Custom Dependencies

Define dependencies for custom extensions.

// Define custom extension dependencies
MathJax.config.loader.dependencies['custom/myextension'] = [
  'input/tex-base',
  '[tex]/ams',
  '[tex]/color'
];

// Register custom extension
MathJax.config.loader.source['custom/myextension'] = '/path/to/my-extension.js';

// Load with automatic dependency resolution
await MathJax.loader.load('custom/myextension');

Performance Optimization

Selective Loading

Load only the components you need to minimize bundle size.

// Minimal configuration for basic TeX
MathJax.config.loader.load = [
  'input/tex-base',  // Basic TeX without extensions
  'output/chtml'     // Lightweight output
];

// Full-featured configuration
MathJax.config.loader.load = [
  'input/tex',       // TeX with common extensions
  '[tex]/ams',       // Mathematical extensions
  '[tex]/color',     // Color support
  'output/svg',      // High-quality output
  'ui/menu',         // User interface
  'a11y/assistive-mml'  // Basic accessibility
];

Bundle Optimization

Use pre-built bundles for common combinations.

// Instead of loading individual components
MathJax.config.loader.load = [
  'input/tex',
  '[tex]/ams',
  '[tex]/newcommand', 
  '[tex]/textmacros',
  '[tex]/noundefined',
  '[tex]/require',
  '[tex]/autoload',
  '[tex]/configmacros',
  'output/chtml'
];

// Use pre-built bundle
// <script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-chtml.js"></script>
// This includes all the above components in a single optimized file

Lazy Loading

Load extensions on demand to improve initial page load.

// Core loading
const core = ['input/tex-base', 'output/chtml'];
await MathJax.loader.load(...core);

// Initial render with basic features
MathJax.typeset();

// Load additional features as needed
const loadExtensions = async (extensions) => {
  await MathJax.loader.load(...extensions);
  MathJax.texReset();  // Reset to recognize new extensions
  MathJax.typeset();   // Re-render with new features
};

// Load on user interaction
document.getElementById('load-ams').addEventListener('click', () => {
  loadExtensions(['[tex]/ams']);
});

document.getElementById('load-chemistry').addEventListener('click', () => {
  loadExtensions(['[tex]/mhchem']);
});

docs

accessibility.md

document-rendering.md

extensions.md

index.md

initialization.md

input-processing.md

output-formats.md

tile.json