or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

advanced-apis.mddocs/

0

# Advanced APIs

1

2

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.

3

4

**Warning:** These APIs are marked as internal and may change between versions. Use with caution in production code.

5

6

## Capabilities

7

8

### Parse Tree Generation

9

10

Parse TeX expressions into KaTeX's internal AST without rendering.

11

12

```typescript { .api }

13

/**

14

* Parse TeX expression into internal parse tree structure

15

* NOTE: Internal API - tree structure may change between versions

16

* @param expression - TeX expression to parse

17

* @param options - KaTeX options

18

* @returns Array of parse nodes representing the expression

19

*/

20

function __parse(expression: string, options: KatexOptions): AnyParseNode[];

21

```

22

23

**Usage Example:**

24

25

```typescript

26

import katex from "katex";

27

28

// Parse without rendering

29

const parseTree = katex.__parse("\\frac{1}{2}", {

30

displayMode: false

31

});

32

33

console.log("Parse tree:", JSON.stringify(parseTree, null, 2));

34

// Inspect the internal structure for custom processing

35

```

36

37

### DOM Tree Rendering

38

39

Generate KaTeX's internal DOM tree structure without converting to markup.

40

41

```typescript { .api }

42

/**

43

* Render TeX to internal DOM tree (HTML + MathML)

44

* NOTE: Internal API - tree structure may change between versions

45

* @param expression - TeX expression to render

46

* @param options - KaTeX options

47

* @returns Internal DOM tree representation

48

*/

49

function __renderToDomTree(expression: string, options: KatexOptions): DomSpan;

50

51

/**

52

* Render TeX to internal DOM tree (HTML only)

53

* NOTE: Internal API - tree structure may change between versions

54

* @param expression - TeX expression to render

55

* @param options - KaTeX options

56

* @returns Internal DOM tree representation

57

*/

58

function __renderToHTMLTree(expression: string, options: KatexOptions): DomSpan;

59

```

60

61

**Usage Examples:**

62

63

```typescript

64

import katex from "katex";

65

66

// Generate internal DOM tree

67

const domTree = katex.__renderToDomTree("E = mc^2", {

68

displayMode: true

69

});

70

71

// Access tree structure

72

console.log("Tree type:", domTree.classes);

73

console.log("Tree children:", domTree.children.length);

74

75

// Convert to actual DOM node

76

const domNode = domTree.toNode();

77

document.body.appendChild(domNode);

78

79

// HTML-only version (no MathML)

80

const htmlTree = katex.__renderToHTMLTree("\\sqrt{x}", {

81

output: "html"

82

});

83

```

84

85

### Font Metrics Extension

86

87

Extend KaTeX's font metrics for custom fonts or symbols.

88

89

```typescript { .api }

90

/**

91

* Extend internal font metrics with custom font data

92

* @param fontMetrics - Object mapping font names to metric data

93

*/

94

function __setFontMetrics(fontMetrics: Record<string, FontMetrics>): void;

95

96

interface FontMetrics {

97

// Font metric properties - see KaTeX source for details

98

[character: string]: [number, number, number, number, number?];

99

}

100

```

101

102

**Usage Example:**

103

104

```typescript

105

import katex from "katex";

106

107

// Add custom font metrics (advanced use case)

108

katex.__setFontMetrics({

109

"MyCustomFont": {

110

"65": [0.68, 0.0, 0.0, 0.0], // Character 'A' metrics

111

"66": [0.68, 0.0, 0.0, 0.0], // Character 'B' metrics

112

// ... more character definitions

113

}

114

});

115

```

116

117

### Symbol Definition

118

119

Define custom symbols and operators.

120

121

```typescript { .api }

122

/**

123

* Add new symbol to KaTeX's symbol table

124

* @param mode - Math mode ("math" or "text")

125

* @param font - Font family for the symbol

126

* @param name - Symbol name/command

127

* @param replace - Character or replacement text

128

* @param mathclass - Symbol classification

129

*/

130

function __defineSymbol(

131

mode: "math" | "text",

132

font: string,

133

name: string,

134

replace: string,

135

mathclass?: string

136

): void;

137

```

138

139

**Usage Example:**

140

141

```typescript

142

import katex from "katex";

143

144

// Define a custom symbol

145

katex.__defineSymbol("math", "main", "\\mystar", "★", "ord");

146

147

// Now can use \mystar in expressions

148

katex.render("\\mystar + \\mystar = 2\\mystar", element);

149

```

150

151

### Function Definition

152

153

Create custom LaTeX functions with parsing and rendering logic.

154

155

```typescript { .api }

156

/**

157

* Define custom LaTeX function

158

* @param funcName - Function name (with backslash)

159

* @param definition - Function definition object

160

*/

161

function __defineFunction(funcName: string, definition: FunctionDefinition): void;

162

163

interface FunctionDefinition {

164

type: string;

165

names: string[];

166

props: {

167

numArgs: number;

168

allowedInText?: boolean;

169

greediness?: number;

170

argTypes?: string[];

171

};

172

handler: (context: any, args: any[]) => any;

173

htmlBuilder?: (group: any, options: any) => any;

174

mathmlBuilder?: (group: any, options: any) => any;

175

}

176

```

177

178

**Usage Example (Advanced):**

179

180

```typescript

181

import katex from "katex";

182

183

// Define a custom \highlight function

184

katex.__defineFunction("\\highlight", {

185

type: "highlight",

186

names: ["\\highlight"],

187

props: {

188

numArgs: 1,

189

allowedInText: true

190

},

191

handler: (context, args) => {

192

return {

193

type: "highlight",

194

mode: context.parser.mode,

195

body: args[0]

196

};

197

},

198

htmlBuilder: (group, options) => {

199

const body = katex.buildCommon.buildExpression(group.body, options);

200

return katex.buildCommon.makeSpan(["highlight"], body, options);

201

}

202

});

203

204

// Usage

205

katex.render("\\highlight{E = mc^2}", element);

206

```

207

208

### Macro Definition

209

210

Define custom macros programmatically.

211

212

```typescript { .api }

213

/**

214

* Define custom macro

215

* @param name - Macro name (with backslash)

216

* @param body - Macro expansion body

217

* @param numArgs - Number of arguments (optional)

218

*/

219

function __defineMacro(name: string, body: string, numArgs?: number): void;

220

```

221

222

**Usage Example:**

223

224

```typescript

225

import katex from "katex";

226

227

// Define custom macros

228

katex.__defineMacro("\\RR", "\\mathbb{R}");

229

katex.__defineMacro("\\diff", "\\frac{\\mathrm{d}#1}{\\mathrm{d}#2}", 2);

230

231

// Use in expressions

232

katex.render("f: \\RR \\to \\RR", element);

233

katex.render("\\diff{f}{x} = f'(x)", element);

234

```

235

236

### DOM Tree Node Types

237

238

Access to internal DOM tree node constructors for custom builders.

239

240

```typescript { .api }

241

const __domTree: {

242

Span: typeof Span;

243

Anchor: typeof Anchor;

244

SymbolNode: typeof SymbolNode;

245

SvgNode: typeof SvgNode;

246

PathNode: typeof PathNode;

247

LineNode: typeof LineNode;

248

};

249

250

// Node constructors for building custom DOM trees

251

class Span {

252

constructor(classes: string[], children?: any[], options?: any);

253

toNode(): HTMLElement;

254

toMarkup(): string;

255

}

256

257

class SymbolNode {

258

constructor(text: string, height?: number, depth?: number, italic?: number);

259

}

260

261

// ... other node types

262

```

263

264

**Usage Example (Very Advanced):**

265

266

```typescript

267

import katex from "katex";

268

269

const { Span, SymbolNode } = katex.__domTree;

270

271

// Build custom DOM tree

272

const customSpan = new Span(["my-custom-class"], [

273

new SymbolNode("x"),

274

new SymbolNode("²")

275

]);

276

277

// Convert to DOM node

278

const domNode = customSpan.toNode();

279

document.body.appendChild(domNode);

280

281

// Or get markup

282

const markup = customSpan.toMarkup();

283

```

284

285

### Settings Schema Access

286

287

Introspect KaTeX's complete options schema.

288

289

```typescript { .api }

290

/**

291

* Complete schema definition for all KaTeX options

292

*/

293

const SETTINGS_SCHEMA: Record<string, OptionSchema>;

294

295

interface OptionSchema {

296

type: string | string[] | { enum: string[] };

297

default?: any;

298

description?: string;

299

processor?: (value: any) => any;

300

cli?: string | false;

301

cliDescription?: string;

302

cliProcessor?: (value: any, previous?: any) => any;

303

}

304

```

305

306

**Usage Example:**

307

308

```typescript

309

import katex from "katex";

310

311

// Examine all available options

312

Object.entries(katex.SETTINGS_SCHEMA).forEach(([key, schema]) => {

313

console.log(`${key}: ${schema.type} (default: ${schema.default})`);

314

console.log(` ${schema.description}`);

315

});

316

317

// Validate option programmatically

318

function validateKatexOption(key: string, value: any): boolean {

319

const schema = katex.SETTINGS_SCHEMA[key];

320

if (!schema) return false;

321

322

if (schema.processor) {

323

try {

324

schema.processor(value);

325

return true;

326

} catch {

327

return false;

328

}

329

}

330

331

return true;

332

}

333

```

334

335

### Integration Examples

336

337

**Custom Renderer:**

338

339

```typescript

340

import katex from "katex";

341

342

class CustomKatexRenderer {

343

constructor(private options: KatexOptions = {}) {}

344

345

renderWithMetrics(tex: string) {

346

// Parse first to analyze structure

347

const parseTree = katex.__parse(tex, this.options);

348

console.log("Expression complexity:", parseTree.length);

349

350

// Render to DOM tree for manipulation

351

const domTree = katex.__renderToDomTree(tex, this.options);

352

353

// Custom processing

354

this.addCustomAttributes(domTree);

355

356

return domTree.toMarkup();

357

}

358

359

private addCustomAttributes(tree: any) {

360

// Add custom data attributes, classes, etc.

361

if (tree.classes) {

362

tree.classes.push("custom-math");

363

}

364

}

365

}

366

```

367

368

**Plugin System:**

369

370

```typescript

371

import katex from "katex";

372

373

class KatexPlugin {

374

static install() {

375

// Define custom functions

376

katex.__defineFunction("\\pluginCmd", {

377

type: "plugin",

378

names: ["\\pluginCmd"],

379

props: { numArgs: 1 },

380

handler: (context, args) => ({ type: "plugin", body: args[0] }),

381

htmlBuilder: (group, options) => {

382

// Custom HTML building logic

383

return new katex.__domTree.Span(["plugin-output"],

384

katex.buildCommon.buildExpression(group.body, options));

385

}

386

});

387

388

// Define custom symbols

389

katex.__defineSymbol("math", "main", "\\pluginSymbol", "◊", "ord");

390

}

391

}

392

393

// Install plugin

394

KatexPlugin.install();

395

```

396

397

### Security and Stability Notes

398

399

- **Internal APIs** may change without notice in minor version updates

400

- **Parse trees** and DOM structures are implementation details

401

- **Custom functions** should validate inputs thoroughly

402

- **Font metrics** changes can affect layout significantly

403

- **Symbol definitions** should not conflict with existing commands

404

405

### Performance Considerations

406

407

- **Parsing** is expensive - cache parse trees when possible

408

- **DOM tree generation** is lighter than full string rendering

409

- **Custom functions** add parsing overhead

410

- **Font metrics** are cached globally

411

- **Symbol lookup** happens frequently during rendering

412

413

### Error Handling

414

415

Internal APIs may throw different errors than public APIs:

416

417

```typescript

418

try {

419

const tree = katex.__parse("\\invalid", {});

420

} catch (error) {

421

if (error instanceof katex.ParseError) {

422

console.log("Parse error:", error.rawMessage);

423

} else {

424

console.log("Internal error:", error.message);

425

}

426

}

427

```