Fast math typesetting for the web.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Internal and advanced KaTeX functions for custom integrations, extensions, and specialized use cases. These APIs provide low-level access to KaTeX's parsing and rendering pipeline.
Warning: These APIs are marked as internal and may change between versions. Use with caution in production code.
Parse TeX expressions into KaTeX's internal AST without rendering.
/**
* Parse TeX expression into internal parse tree structure
* NOTE: Internal API - tree structure may change between versions
* @param expression - TeX expression to parse
* @param options - KaTeX options
* @returns Array of parse nodes representing the expression
*/
function __parse(expression: string, options: KatexOptions): AnyParseNode[];Usage Example:
import katex from "katex";
// Parse without rendering
const parseTree = katex.__parse("\\frac{1}{2}", {
displayMode: false
});
console.log("Parse tree:", JSON.stringify(parseTree, null, 2));
// Inspect the internal structure for custom processingGenerate KaTeX's internal DOM tree structure without converting to markup.
/**
* Render TeX to internal DOM tree (HTML + MathML)
* NOTE: Internal API - tree structure may change between versions
* @param expression - TeX expression to render
* @param options - KaTeX options
* @returns Internal DOM tree representation
*/
function __renderToDomTree(expression: string, options: KatexOptions): DomSpan;
/**
* Render TeX to internal DOM tree (HTML only)
* NOTE: Internal API - tree structure may change between versions
* @param expression - TeX expression to render
* @param options - KaTeX options
* @returns Internal DOM tree representation
*/
function __renderToHTMLTree(expression: string, options: KatexOptions): DomSpan;Usage Examples:
import katex from "katex";
// Generate internal DOM tree
const domTree = katex.__renderToDomTree("E = mc^2", {
displayMode: true
});
// Access tree structure
console.log("Tree type:", domTree.classes);
console.log("Tree children:", domTree.children.length);
// Convert to actual DOM node
const domNode = domTree.toNode();
document.body.appendChild(domNode);
// HTML-only version (no MathML)
const htmlTree = katex.__renderToHTMLTree("\\sqrt{x}", {
output: "html"
});Extend KaTeX's font metrics for custom fonts or symbols.
/**
* Extend internal font metrics with custom font data
* @param fontMetrics - Object mapping font names to metric data
*/
function __setFontMetrics(fontMetrics: Record<string, FontMetrics>): void;
interface FontMetrics {
// Font metric properties - see KaTeX source for details
[character: string]: [number, number, number, number, number?];
}Usage Example:
import katex from "katex";
// Add custom font metrics (advanced use case)
katex.__setFontMetrics({
"MyCustomFont": {
"65": [0.68, 0.0, 0.0, 0.0], // Character 'A' metrics
"66": [0.68, 0.0, 0.0, 0.0], // Character 'B' metrics
// ... more character definitions
}
});Define custom symbols and operators.
/**
* Add new symbol to KaTeX's symbol table
* @param mode - Math mode ("math" or "text")
* @param font - Font family for the symbol
* @param name - Symbol name/command
* @param replace - Character or replacement text
* @param mathclass - Symbol classification
*/
function __defineSymbol(
mode: "math" | "text",
font: string,
name: string,
replace: string,
mathclass?: string
): void;Usage Example:
import katex from "katex";
// Define a custom symbol
katex.__defineSymbol("math", "main", "\\mystar", "★", "ord");
// Now can use \mystar in expressions
katex.render("\\mystar + \\mystar = 2\\mystar", element);Create custom LaTeX functions with parsing and rendering logic.
/**
* Define custom LaTeX function
* @param funcName - Function name (with backslash)
* @param definition - Function definition object
*/
function __defineFunction(funcName: string, definition: FunctionDefinition): void;
interface FunctionDefinition {
type: string;
names: string[];
props: {
numArgs: number;
allowedInText?: boolean;
greediness?: number;
argTypes?: string[];
};
handler: (context: any, args: any[]) => any;
htmlBuilder?: (group: any, options: any) => any;
mathmlBuilder?: (group: any, options: any) => any;
}Usage Example (Advanced):
import katex from "katex";
// Define a custom \highlight function
katex.__defineFunction("\\highlight", {
type: "highlight",
names: ["\\highlight"],
props: {
numArgs: 1,
allowedInText: true
},
handler: (context, args) => {
return {
type: "highlight",
mode: context.parser.mode,
body: args[0]
};
},
htmlBuilder: (group, options) => {
const body = katex.buildCommon.buildExpression(group.body, options);
return katex.buildCommon.makeSpan(["highlight"], body, options);
}
});
// Usage
katex.render("\\highlight{E = mc^2}", element);Define custom macros programmatically.
/**
* Define custom macro
* @param name - Macro name (with backslash)
* @param body - Macro expansion body
* @param numArgs - Number of arguments (optional)
*/
function __defineMacro(name: string, body: string, numArgs?: number): void;Usage Example:
import katex from "katex";
// Define custom macros
katex.__defineMacro("\\RR", "\\mathbb{R}");
katex.__defineMacro("\\diff", "\\frac{\\mathrm{d}#1}{\\mathrm{d}#2}", 2);
// Use in expressions
katex.render("f: \\RR \\to \\RR", element);
katex.render("\\diff{f}{x} = f'(x)", element);Access to internal DOM tree node constructors for custom builders.
const __domTree: {
Span: typeof Span;
Anchor: typeof Anchor;
SymbolNode: typeof SymbolNode;
SvgNode: typeof SvgNode;
PathNode: typeof PathNode;
LineNode: typeof LineNode;
};
// Node constructors for building custom DOM trees
class Span {
constructor(classes: string[], children?: any[], options?: any);
toNode(): HTMLElement;
toMarkup(): string;
}
class SymbolNode {
constructor(text: string, height?: number, depth?: number, italic?: number);
}
// ... other node typesUsage Example (Very Advanced):
import katex from "katex";
const { Span, SymbolNode } = katex.__domTree;
// Build custom DOM tree
const customSpan = new Span(["my-custom-class"], [
new SymbolNode("x"),
new SymbolNode("²")
]);
// Convert to DOM node
const domNode = customSpan.toNode();
document.body.appendChild(domNode);
// Or get markup
const markup = customSpan.toMarkup();Introspect KaTeX's complete options schema.
/**
* Complete schema definition for all KaTeX options
*/
const SETTINGS_SCHEMA: Record<string, OptionSchema>;
interface OptionSchema {
type: string | string[] | { enum: string[] };
default?: any;
description?: string;
processor?: (value: any) => any;
cli?: string | false;
cliDescription?: string;
cliProcessor?: (value: any, previous?: any) => any;
}Usage Example:
import katex from "katex";
// Examine all available options
Object.entries(katex.SETTINGS_SCHEMA).forEach(([key, schema]) => {
console.log(`${key}: ${schema.type} (default: ${schema.default})`);
console.log(` ${schema.description}`);
});
// Validate option programmatically
function validateKatexOption(key: string, value: any): boolean {
const schema = katex.SETTINGS_SCHEMA[key];
if (!schema) return false;
if (schema.processor) {
try {
schema.processor(value);
return true;
} catch {
return false;
}
}
return true;
}Custom Renderer:
import katex from "katex";
class CustomKatexRenderer {
constructor(private options: KatexOptions = {}) {}
renderWithMetrics(tex: string) {
// Parse first to analyze structure
const parseTree = katex.__parse(tex, this.options);
console.log("Expression complexity:", parseTree.length);
// Render to DOM tree for manipulation
const domTree = katex.__renderToDomTree(tex, this.options);
// Custom processing
this.addCustomAttributes(domTree);
return domTree.toMarkup();
}
private addCustomAttributes(tree: any) {
// Add custom data attributes, classes, etc.
if (tree.classes) {
tree.classes.push("custom-math");
}
}
}Plugin System:
import katex from "katex";
class KatexPlugin {
static install() {
// Define custom functions
katex.__defineFunction("\\pluginCmd", {
type: "plugin",
names: ["\\pluginCmd"],
props: { numArgs: 1 },
handler: (context, args) => ({ type: "plugin", body: args[0] }),
htmlBuilder: (group, options) => {
// Custom HTML building logic
return new katex.__domTree.Span(["plugin-output"],
katex.buildCommon.buildExpression(group.body, options));
}
});
// Define custom symbols
katex.__defineSymbol("math", "main", "\\pluginSymbol", "◊", "ord");
}
}
// Install plugin
KatexPlugin.install();Internal APIs may throw different errors than public APIs:
try {
const tree = katex.__parse("\\invalid", {});
} catch (error) {
if (error instanceof katex.ParseError) {
console.log("Parse error:", error.rawMessage);
} else {
console.log("Internal error:", error.message);
}
}