npm.io
0.1.1 • Published yesterday

@m2d/math

Licence
MIT
Version
0.1.1
Deps
2
Size
22 kB
Vulns
0
Weekly
0
Stars
1

@m2d/math

CI codecov npm version npm downloads npm bundle size license

@m2d/math: LaTeX Math to Word DOCX plugin for @m2d/core. Transforms inline and block math into native editable Word OpenXML equations.


Features

  • Native Word Equations: Converts LaTeX math into native docx.Math structures (MathRun, MathFraction, MathRadical, MathSuperScript, MathSubScript) — completely editable in Microsoft Word with crisp vector rendering.
  • Rich Mathematical Macros: Comprehensive support for fractions (\frac), roots (\sqrt), superscripts (^), subscripts (_), summations (\sum), integrals (\int), products (\prod), Greek letters, and standard mathematical relations.
  • Delimiter Boundary Guards: Protects against runaway parsing caused by unescaped currency symbols or unclosed delimiters by checking for structural markdown markers.
  • Flexible Error Modes: Choose between styled inline/block warning badges (warn), raw monospace code fallbacks (raw), or strict pipeline errors (throw).
  • Lightweight & Fast: Zero browser or heavy rendering engine overhead — converts LaTeX AST to Word OpenXML in pure TypeScript.

Installation

$ pnpm add @m2d/math remark-math @m2d/core docx

or

$ npm install @m2d/math remark-math @m2d/core docx

or

$ yarn add @m2d/math remark-math @m2d/core docx

Quick Start

import { toDocx } from "@m2d/core";
import { mathPlugin } from "@m2d/math";
import remarkMath from "remark-math";
import remarkParse from "remark-parse";
import { unified } from "unified";

const markdown = `
# Physics Notes

Einstein's mass-energy equivalence is expressed as $E = mc^2$.

A quadratic formula:

$
x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}
$
`;

// 1. Parse markdown with remark-math to generate math AST nodes
const mdast = unified().use(remarkParse).use(remarkMath).parse(markdown);

// 2. Convert to DOCX with the math plugin
const docxBlob = await toDocx(mdast, {}, {
  plugins: [mathPlugin()],
});

Plugin Options

export interface IMathPluginOptions {
  /**
   * Error handling strategy when LaTeX parsing fails or runaway syntax is detected.
   * - "warn": Emits a styled warning text badge: `⚠️ [Math Syntax Error: ...]`
   * - "raw": Emits the raw formula string as monospace code text
   * - "throw": Re-throws the underlying parse error
   * @default "warn"
   */
  errorMode?: "warn" | "raw" | "throw";

  /**
   * Maximum character length allowed for inline equations.
   * Prevents runaway AST nodes when unclosed dollar signs occur.
   * @default 1000
   */
  maxInlineLength?: number;
}

Deep Dive Guides


License

This library is licensed under the MIT open-source license.


with by Mayank Kumar Chaudhari

Keywords