or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

accessibility.mdadvanced-apis.mdauto-rendering.mdchemistry.mdcli.mdconfiguration.mdcopy-tex.mdcore-rendering.mdindex.mdmathtex-script-type.md
tile.json

tessl/npm-katex

Fast math typesetting for the web.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/katex@0.16.x

To install, run

npx @tessl/cli install tessl/npm-katex@0.16.0

index.mddocs/

KaTeX

KaTeX is the fastest math typesetting library for the web. It renders TeX math expressions using pure CSS/HTML without relying on MathJax, enabling blazing-fast client-side and server-side math rendering with high-quality output that's identical across all browsers.

Package Information

  • Package Name: katex
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install katex

Core Imports

import katex from "katex";

For ESM named imports:

import { render, renderToString, ParseError } from "katex";

For CommonJS:

const katex = require("katex");
const { render, renderToString } = require("katex");

Basic Usage

import katex from "katex";

// Render to DOM element
const element = document.getElementById("math");
katex.render("c = \\pm\\sqrt{a^2 + b^2}", element, {
  throwOnError: false
});

// Render to HTML string
const html = katex.renderToString("\\frac{1}{2}", {
  displayMode: true
});

// Handle errors
try {
  katex.render("\\invalid", element);
} catch (error) {
  if (error instanceof katex.ParseError) {
    console.log("Parse error at position:", error.position);
  }
}

Architecture

KaTeX is built around several key components:

  • Core Rendering Engine: Fast TeX-to-HTML/MathML conversion with DOM and string output modes
  • Parser: Recursive descent parser that converts TeX expressions into internal parse trees
  • Settings System: Comprehensive configuration for output format, error handling, and LaTeX compatibility
  • Extension System: Pluggable contrib modules for auto-rendering, chemistry, accessibility, and clipboard integration
  • CLI Interface: Command-line tool for server-side rendering and batch processing

Capabilities

Core Rendering

Primary rendering functions that convert TeX expressions to DOM elements or HTML strings.

function render(tex: string, element: HTMLElement, options?: KatexOptions): void;
function renderToString(tex: string, options?: KatexOptions): string;

Core Rendering

Auto-Rendering

Automatic math detection and rendering within HTML elements, supporting multiple delimiter types.

function renderMathInElement(element: Element, options?: AutoRenderOptions): void;

interface AutoRenderOptions extends KatexOptions {
  delimiters?: DelimiterConfig[];
  ignoredTags?: string[];
  ignoredClasses?: string[];
  errorCallback?: (msg: string, err: Error) => void;
  preProcess?: (math: string) => string;
}

Auto-Rendering

Chemistry Rendering

Chemical equation and formula rendering through the mhchem extension.

// Available as LaTeX macros when mhchem is imported:
// \ce{H2O} - Chemical equations and formulas
// \pu{1.2e3 kg*m/s^2} - Physical units
// \tripledash - Chemical bonds

Chemistry Rendering

Configuration and Error Handling

Comprehensive options system and error handling for controlling output format and behavior.

interface KatexOptions {
  displayMode?: boolean;
  output?: "html" | "mathml" | "htmlAndMathml";
  throwOnError?: boolean;
  errorColor?: string;
  macros?: Record<string, string | object | ((context: any) => string | object)>;
  strict?: boolean | "ignore" | "warn" | "error" | StrictFunction;
  trust?: boolean | TrustFunction;
  maxSize?: number;
  maxExpand?: number;
  // ... additional options
}

class ParseError extends Error {
  name: "ParseError";
  position: number;
  length: number;
  rawMessage: string;
}

Configuration

Accessibility

Screen reader support and accessibility string generation for math expressions.

function renderA11yString(tex: string, settings?: KatexOptions): string;

Accessibility

CLI Interface

Command-line interface for server-side rendering and batch processing.

# Basic usage
katex --input input.tex --output output.html

# With options
katex --display-mode --no-throw-on-error --error-color ff0000

CLI Interface

Copy-TeX Extension

Clipboard integration for copying rendered math as TeX source code.

import "katex/contrib/copy-tex";
// Automatically enhances copy behavior for .katex elements

Copy-TeX Extension

MathTeX Script Type Extension

Automatic rendering of <script type="math/tex"> elements for CMS integration.

import "katex/contrib/mathtex-script-type";
// Automatically processes all script[type*="math/tex"] elements

MathTeX Script Type

Advanced APIs

Internal and advanced functions for custom integrations and extensions.

function __parse(expression: string, options: KatexOptions): AnyParseNode[];
function __renderToDomTree(expression: string, options: KatexOptions): DomSpan;
function __renderToHTMLTree(expression: string, options: KatexOptions): DomSpan;
function __setFontMetrics(fontMetrics: Record<string, FontMetrics>): void;
function __defineSymbol(mode: string, font: string, name: string, replace: string, mathclass?: string): void;
function __defineFunction(funcName: string, definition: FunctionDefinition): void;
function __defineMacro(name: string, body: string, numArgs?: number): void;

Advanced APIs

Types

interface KatexOptions {
  displayMode?: boolean;
  output?: "html" | "mathml" | "htmlAndMathml";
  leqno?: boolean;
  fleqn?: boolean;
  throwOnError?: boolean;
  errorColor?: string;
  macros?: Record<string, string | object | ((macroExpander: object) => string | object)>;
  minRuleThickness?: number;
  colorIsTextColor?: boolean;
  maxSize?: number;
  maxExpand?: number;
  strict?: boolean | "ignore" | "warn" | "error" | StrictFunction;
  trust?: boolean | TrustFunction;
  globalGroup?: boolean;
}

type StrictFunction = (
  errorCode: "unknownSymbol" | "unicodeTextInMathMode" | "mathVsTextUnits" | "commentAtEnd" | "htmlExtension" | "newLineInDisplayMode",
  errorMsg: string,
  token: Token
) => boolean | "error" | "warn" | "ignore" | undefined;

type TrustContext = 
  | { command: "\\url", url: string, protocol?: string }
  | { command: "\\href", url: string, protocol?: string }
  | { command: "\\includegraphics", url: string, protocol?: string }
  | { command: "\\htmlClass", class: string }
  | { command: "\\htmlId", id: string }
  | { command: "\\htmlStyle", style: string }
  | { command: "\\htmlData", attributes: Record<string, string> };

type TrustFunction = (context: TrustContext) => boolean;

class ParseError extends Error {
  name: "ParseError";
  position: number;
  length: number;
  rawMessage: string;
  message: string;
  constructor(message: string, token?: object);
}

interface Token {
  text: string;
  loc: SourceLocation | undefined;
  noexpand?: boolean;
  treatAsRelax?: boolean;
}

interface SourceLocation {
  start: number;
  end: number;
  lexer: Lexer;
}

interface Lexer {
  input: string;
  tokenRegex: RegExp;
  settings: Required<KatexOptions>;
  catcodes: Record<string, number>;
}