feat: math from LaTeX in docx/math, with accents, bars, braces, boxes, phantoms and large operators (#3570)

* feat: math from LaTeX in docx/math, with accents, bars, braces, boxes, phantoms and large operators

latexToMath turns LaTeX math into docx's math components, to go in a Math.
It reads what LaTeX, MathJax and KaTeX write: fractions, roots, scripts,
large operators, functions, \left and \right, accents, braces, boxes,
fonts, \text, and the environments for matrices, cases and aligned
equations, with \tag. It throws for what it can't read, saying where.

The parts LaTeX needs are public components too: MathLargeOperator,
MathAccent, MathBar, MathBrace, MathBox and MathPhantom in docx/math, and
in docx, MathRun's style, script and literal, MathFraction's type, and
limits on MathSum and MathIntegral.

Closes #2994

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: draw MathRun alphabets upright unless given a style, and escape the \middle| table cell

A run with a script but no style wrote no m:sty, which Word draws as italic, so sansSerif came out italic
sans-serif rather than the upright 𝖠 its docs show. A script other than roman now defaults to a plain style,
as LaTeX draws its alphabets; a given style is kept. latexToMath already gave each alphabet its style.

The | after \middle in the LaTeX docs' table ended the cell, splitting the row into three.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Dolan
2026-09-28 17:07:59 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 5213b31aae
commit eb206519ae
38 changed files with 4815 additions and 26 deletions
+77
View File
@@ -0,0 +1,77 @@
// Math from LaTeX (issue #2994): each equation's LaTeX, and the equation latexToMath makes of it. See docs/usage/math-latex.md.
import * as fs from "fs";
import { AlignmentType, Document, HeadingLevel, Packer, Paragraph, TextRun } from "docx";
import { Math, latexToMath } from "docx/math";
const heading = (text: string): Paragraph => new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun(text)] });
// The LaTeX, then its equation on a line of its own, centred
const example = (latex: string): readonly Paragraph[] => [
new Paragraph({ children: [new TextRun({ text: latex, font: "Courier New", size: 18 })] }),
new Paragraph({ alignment: AlignmentType.CENTER, children: [new Math({ children: latexToMath(latex) })] }),
];
const doc = new Document({
sections: [
{
children: [
new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("Math from LaTeX")] }),
new Paragraph({
children: [
new TextRun("Inline math, such as "),
new Math({ children: latexToMath("$e^{i\\pi} + 1 = 0$") }),
new TextRun(", goes in a paragraph with its text."),
],
}),
heading("Fractions, roots and scripts"),
...example("x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}"),
...example("\\sqrt[3]{x^3 + y^3} \\quad \\binom{n}{k} = \\frac{n!}{k!\\,(n-k)!} \\quad {}^{14}_{6}\\mathrm{C}"),
...example("f'(x) = \\lim_{h \\to 0} \\frac{f(x+h) - f(x)}{h}"),
heading("Sums, integrals and other large operators"),
...example("\\sum_{i=1}^{n} i^2 = \\frac{n(n+1)(2n+1)}{6}"),
...example("\\int_{-\\infty}^{\\infty} e^{-x^2}\\,dx = \\sqrt{\\pi} \\qquad \\oint_C \\mathbf{F} \\cdot d\\mathbf{r}"),
...example(
"\\prod_{p \\text{ prime}} \\frac{1}{1 - p^{-s}} \\qquad \\bigcup_{i \\in I} A_i \\qquad \\sum\\nolimits_{k} a_k",
),
heading("Functions and brackets"),
...example("\\sin^2\\theta + \\cos^2\\theta = 1 \\qquad \\log_2 n \\qquad \\operatorname{rank}(A)"),
...example(
"\\left( \\frac{a}{b} \\right)^2 \\quad \\left\\| \\mathbf{v} \\right\\| \\quad \\left\\langle \\psi \\middle| \\phi \\right\\rangle \\quad \\lfloor x \\rfloor",
),
heading("Accents, braces and boxes"),
...example(
"\\hat{x} \\quad \\bar{x} \\quad \\vec{v} \\quad \\dot{x} \\quad \\ddot{x} \\quad \\tilde{n} \\quad \\overline{AB} \\quad \\underline{x}",
),
...example("\\underbrace{1 + 2 + \\cdots + n}_{n \\text{ terms}} \\qquad \\overbrace{a + b}^{c}"),
...example("\\boxed{E = mc^2} \\qquad \\frac{\\cancel{2} x}{\\cancel{2}} = x \\qquad A \\xrightarrow{f} B"),
heading("Fonts and symbols"),
...example("\\forall \\varepsilon > 0\\; \\exists \\delta > 0 : |x - a| < \\delta \\implies |f(x) - f(a)| < \\varepsilon"),
...example(
"\\mathbb{R}^n \\quad \\mathcal{L} \\quad \\mathfrak{g} \\quad \\mathbf{F} = m\\mathbf{a} \\quad \\boldsymbol{\\alpha} \\quad A \\not\\subset B",
),
...example("\\nabla \\times \\mathbf{E} = -\\frac{\\partial \\mathbf{B}}{\\partial t}"),
heading("Matrices and cases"),
...example(
"A = \\begin{pmatrix} a_{11} & a_{12} & \\cdots \\\\ a_{21} & a_{22} & \\cdots \\\\ \\vdots & \\vdots & \\ddots \\end{pmatrix}",
),
...example("\\det \\begin{vmatrix} a & b \\\\ c & d \\end{vmatrix} = ad - bc"),
...example("|x| = \\begin{cases} x & \\text{if } x \\ge 0 \\\\ -x & \\text{otherwise} \\end{cases}"),
heading("Aligned equations"),
...example("\\begin{aligned} (a+b)^2 &= (a+b)(a+b) \\\\ &= a^2 + 2ab + b^2 \\end{aligned}"),
...example("\\begin{align} y &= mx + b \\tag{1} \\\\ y' &= m \\tag{2} \\end{align}"),
],
},
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
+1
View File
@@ -65,6 +65,7 @@
- [Tabs](usage/tabs.md)
- [Change Tracking](usage/change-tracking.md)
- [Math](usage/math.md)
- [Math from LaTeX](usage/math-latex.md)
- [Comments](usage/comments.md)
- [Footnotes](usage/footnotes.md)
- [Endnotes](usage/endnotes.md)
+180
View File
@@ -0,0 +1,180 @@
# Math from LaTeX
<!-- cspell:ignore binom infty textrm pmatrix bmatrix Bmatrix vmatrix Vmatrix smallmatrix dcases rcases alignat alignedat flalign eqnarray gathered multline displaymath subarray substack mathbb mathcal mathscr mathfrak mathsf mathtt mathrm mathit mathbf boldsymbol textbf operatorname overbrace underbrace overbracket underbracket overparen underparen overset underset stackrel xrightarrow xleftarrow bcancel xcancel hphantom vphantom mathstrut nolimits bigcup bigcap bigoplus bigotimes iint iiint oint nicefrac sfrac dfrac tfrac cfrac dbinom tbinom lvert rvert langle rangle lfloor rfloor lceil rceil pmod bmod varepsilon newcommand textcolor widehat widetilde ddot dddot mathring overrightarrow overleftarrow Bigl Bigr biggl biggr texmath -->
!> Math from LaTeX requires an understanding of [Math](usage/math.md).
`latexToMath` turns LaTeX math into `docx`'s math components. They go in a `Math`, as any others do, and Word shows and edits them as equations, as it does those typed into it.
It reads the math that LaTeX, MathJax and KaTeX write, which is what most tools that write math give, such as a language model's answer or a Markdown document.
## Example
```ts live
import { AlignmentType, Document, Paragraph } from "docx";
import { Math, latexToMath } from "docx/math";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
alignment: AlignmentType.CENTER,
children: [new Math({ children: latexToMath("x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}") })],
}),
],
},
],
});
```
In JavaScript strings, each backslash is written twice: `"\\frac"` is LaTeX's `\frac`. A template literal with `String.raw` saves doubling them: ``String.raw`\frac{a}{b}` ``.
## Inline and display math
Math in a paragraph with text is inline, as LaTeX's `$…$`. Math in a paragraph of its own is display math, as `$$…$$`, and is best centred. `latexToMath` leaves out the delimiters `$…$`, `$$…$$`, `\(…\)` and `\[…\]`, so LaTeX can be given with them or without.
```ts live
import { AlignmentType, Document, Paragraph, TextRun } from "docx";
import { Math, latexToMath } from "docx/math";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
new TextRun("Euler's identity, "),
new Math({ children: latexToMath("$e^{i\\pi} + 1 = 0$") }),
new TextRun(", links five constants. Summed, the first n squares are:"),
],
}),
new Paragraph({
alignment: AlignmentType.CENTER,
children: [new Math({ children: latexToMath("$$\\sum_{i=1}^{n} i^2 = \\frac{n(n+1)(2n+1)}{6}$$") })],
}),
],
},
],
});
```
## Mixing with components
`latexToMath` gives a list of components, which can go among others anywhere math goes, such as in a fraction or a matrix:
```ts live
import { Document, Paragraph } from "docx";
import { Math, MathFraction, MathRun, latexToMath } from "docx/math";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
new Math({
children: [
new MathRun("f(x)="),
new MathFraction({
numerator: latexToMath("\\sin x"),
denominator: latexToMath("\\sqrt{1 + x^2}"),
}),
],
}),
],
}),
],
},
],
});
```
## Matrices, cases and aligned equations
LaTeX's environments become matrices, cases and aligned equations. `\tag` gives an equation its number:
```ts live
import { AlignmentType, Document, Paragraph } from "docx";
import { Math, latexToMath } from "docx/math";
const equation = (latex: string): Paragraph =>
new Paragraph({ alignment: AlignmentType.CENTER, children: [new Math({ children: latexToMath(latex) })] });
const doc = new Document({
sections: [
{
children: [
equation("A = \\begin{pmatrix} 1 & 2 \\\\ 3 & 4 \\end{pmatrix}"),
equation("|x| = \\begin{cases} x & \\text{if } x \\ge 0 \\\\ -x & \\text{otherwise} \\end{cases}"),
equation("\\begin{align} y &= mx + b \\tag{1} \\\\ y' &= m \\tag{2} \\end{align}"),
],
},
],
});
```
## What it reads
| LaTeX | Math |
| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- |
| Letters, digits, `+ - = < >`, and characters such as `α` and `≤` typed as they are | `MathRun`, one for each run of text in the same font. `-` is written as the minus sign `−` |
| Greek letters, symbols, relations, arrows and dots, such as `\alpha`, `\infty`, `\le`, `\to`, `\cdots` | Their characters. Capital Greek letters are upright, as in LaTeX |
| `x^2`, `x_i`, `x_i^2`, `f'`, `{}^{14}_6\mathrm{C}` | `MathSuperScript`, `MathSubScript`, `MathSubSuperScript` |
| `\frac`, `\dfrac`, `\tfrac`, `\cfrac`, `{a \over b}` | `MathFraction` |
| `\nicefrac`, `\sfrac` | `MathFraction` with `type: "skewed"` |
| `\binom`, `\dbinom`, `\tbinom`, `{n \choose k}`, `{a \atop b}` | `MathFraction` with `type: "noBar"`, in `MathBrackets` for a binomial |
| `\sqrt{x}`, `\sqrt[3]{x}` | `MathRadical` |
| `\sum`, `\prod`, `\coprod`, `\int`, `\iint`, `\iiint`, `\oint`, `\bigcup`, `\bigcap`, `\bigoplus` … | `MathLargeOperator`, with `\limits` and `\nolimits` as `limits` |
| `\sin`, `\cos`, `\log`, `\ln`, `\exp`, `\operatorname{rank}` … | `MathFunction`, with its name upright |
| `\lim`, `\max`, `\min`, `\sup`, `\inf`, `\det`, `\operatorname*{argmax}` … | `MathFunction`, with its limits below its name (`MathLimitLower`) |
| `\left( … \middle\| … \right)`, with any delimiters, and `.` for none | `MathBrackets`, which grow with what they hold |
| `\big(`, `\Bigl[`, `\biggr)` … | The bracket, which doesn't grow |
| `\hat`, `\bar`, `\vec`, `\dot`, `\ddot`, `\tilde`, `\widehat`, `\overrightarrow` … | `MathAccent` |
| `\overline`, `\underline` | `MathBar` |
| `\overbrace{…}^{…}`, `\underbrace{…}_{…}`, `\overbracket`, `\underparen` … | `MathBrace`, with the script as its label |
| `\overset`, `\underset`, `\stackrel`, `\xrightarrow[below]{above}` … | `MathLimitUpper`, `MathLimitLower` |
| `\boxed`, `\cancel`, `\bcancel`, `\xcancel` | `MathBox` |
| `\phantom`, `\hphantom`, `\vphantom`, `\smash` | `MathPhantom` |
| `\mathrm`, `\mathit`, `\mathbf`, `\boldsymbol`, and `\rm`, `\bf` in a group | `MathRun` with a `style` |
| `\mathbb`, `\mathcal`, `\mathscr`, `\mathfrak`, `\mathsf`, `\mathtt` | `MathRun` with a `script` |
| `\text`, `\textrm`, `\mbox` …, which can hold `$…$` | `MathRun` with `normalText` |
| `\,`, `\:`, `\;`, `\quad`, `\qquad`, `~` | Spaces of their widths |
| `\not=`, `\not\in` … | The relation with a line through it, such as `≠` |
| `\bmod`, `\pmod{n}` | mod, upright |
| `matrix`, `pmatrix`, `bmatrix`, `Bmatrix`, `vmatrix`, `Vmatrix`, `smallmatrix`, `array`, `\substack` | `MathMatrix` |
| `cases`, `dcases`, `rcases` | `MathCases` |
| `align`, `aligned`, `alignat`, `gather`, `gathered`, `split`, `multline`, `eqnarray` | `MathEquationArray`, with a row's `\tag{1}` as its `equationNumber`, `"(1)"` |
| `equation` | Its math, or a `MathEquationArray` of one row with a `\tag` |
| `a &= b \\ &= c` outside an environment | `MathEquationArray`, as MathJax reads it |
| `\displaystyle`, `\label`, `\nonumber`, `\hline`, `\color`, `\textcolor` … | Nothing: Word works out sizes itself, and its math has no colours of its own. `\textcolor`'s math stays |
A large operator or a function applies to the math after it, up to a relation such as `=`, a `+` or `−`, a comma, or another operator, outside brackets. So `\sum_i a_i + b` applies the sum to `a_i`, and `\int_0^1 f(x)\,dx` applies the integral to `f(x)\,dx`. LaTeX doesn't say, and Word draws them the same either way. It matters only when the equation is edited in Word.
## What it doesn't read
`latexToMath` throws an error for anything it doesn't read, which says what and where, such as:
```
latexToMath: unknown command \foo, at character 10 of "\frac{a}{\foo}"
```
Catch it to write the LaTeX some other way, such as in a `TextRun`. These aren't read, or are read only in part:
- commands defined with `\newcommand` or `\def`, which can be replaced in the text first;
- spacing in units: `\hspace{…}` is written as a quad, and `\kern` isn't read;
- `\textbf{…}` is written as normal text, not bold;
- LaTeX's automatic equation numbers: `align` numbers its rows only with `\tag`.
## Compatibility
Word is the reference: `latexToMath` writes what Word writes for each. Other applications draw less of it:
- **LibreOffice** draws only ∑, ∏, ∐ and the integrals as large operators, and draws `¿` for others, such as ⋃. It draws `\mathbb` letters, but not bold, script or fraktur ones, and doesn't draw boxes or lines struck through. It shows the `&` and `#` of aligned equations, as [Math](usage/math.md) says.
- **Pages** draws all but `\boxed`'s box, and shows the `#` before equation numbers.
## Demo
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/math/latex.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/math/latex.ts_
+321 -1
View File
@@ -1,5 +1,7 @@
# Math
<!-- cspell:ignore binom -->
!> Math requires an understanding of [Sections](usage/sections.md) and [Paragraphs](usage/paragraph.md).
## Intro
@@ -18,7 +20,9 @@ import { Document, Packer, Paragraph } from "docx";
import { Math, MathFraction, MathRun } from "docx/math";
```
Types such as `IMathOptions` and `MathComponent` come from `docx/math` too. `docx` still exports the math it had before `docx/math`, so code that imports it from `docx` keeps working. The two export the same classes, so they can be mixed. `MathMatrix`, `MathCases`, `MathEquationArray` and `MathBrackets` come from `docx/math` only.
Types such as `IMathOptions` and `MathComponent` come from `docx/math` too. `docx` still exports the math it had before `docx/math`, so code that imports it from `docx` keeps working. The two export the same classes, so they can be mixed. `MathMatrix`, `MathCases`, `MathEquationArray`, `MathBrackets`, `MathLargeOperator`, `MathAccent`, `MathBar`, `MathBrace`, `MathBox`, `MathPhantom` and `latexToMath` come from `docx/math` only.
To write math from LaTeX, such as `\frac{a}{b}`, see [Math from LaTeX](usage/math-latex.md).
In a page without a bundler, load `dist/math.umd.cjs` after `dist/index.umd.cjs` (or `dist/math.iife.js` after `dist/index.iife.js`). It adds a `docxMath` global, such as `new docxMath.MathRun("2+2")`.
@@ -157,6 +161,45 @@ const doc = new Document({
});
```
#### Styles and alphabets
A run's letters can be upright, bold or both, as LaTeX's `\mathrm`, `\mathbf` and `\boldsymbol` (`style`), and in another alphabet, such as double-struck for ℝ or script for ℒ (`script`):
```ts live
import { Document, Paragraph } from "docx";
import { Math, MathRun } from "docx/math";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
new Math({
children: [
new MathRun({ text: "R", script: "doubleStruck" }),
new MathRun({ text: "L", script: "script" }),
new MathRun({ text: "F", style: "bold" }),
new MathRun("=m"),
new MathRun({ text: "a", style: "bold" }),
],
}),
],
}),
],
},
],
});
```
| Option | Type | Default | Notes |
| ------------ | ---------------------------------------------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `text` | `string` | | |
| `normalText` | `boolean` | `false` | Upright, in the document's font, with its spaces kept (`m:nor`). Not with `style` or `script` |
| `style` | `"plain"`, `"bold"`, `"italic"`, `"boldItalic"` | | Upright, bold, italic, or both (`m:sty`). Word draws letters in italic unless a run has a style, or an alphabet other than roman |
| `script` | `"roman"`, `"script"`, `"fraktur"`, `"doubleStruck"`, `"sansSerif"`, `"monospace"` | | The alphabet (`m:scr`): 𝒜, 𝔄, 𝔸, 𝖠 and 𝙰 |
| `literal` | `boolean` | `false` | Takes the text as it is (`m:lit`), such as an `&` in a `MathEquationArray`, which would otherwise be a point the rows line up at |
### Math Fraction
`MathFractions` require a `numerator` and a `denominator`, which are both a list of `MathComponents`
@@ -254,6 +297,41 @@ const doc = new Document({
});
```
#### Fraction types
A fraction can be skewed, as ½, linear, as a/b, or stacked with no bar, as in a binomial coefficient (`type`, `m:type`):
```ts live
import { Document, Paragraph } from "docx";
import { Math, MathFraction, MathRoundBrackets, MathRun } from "docx/math";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
new Math({
children: [
new MathFraction({ numerator: [new MathRun("1")], denominator: [new MathRun("2")], type: "skewed" }),
new MathFraction({ numerator: [new MathRun("a")], denominator: [new MathRun("b")], type: "linear" }),
new MathRoundBrackets({
children: [
new MathFraction({ numerator: [new MathRun("n")], denominator: [new MathRun("k")], type: "noBar" }),
],
}),
],
}),
],
}),
],
},
],
});
```
`type` is `"stacked"` (the default), `"skewed"`, `"linear"` or `"noBar"`.
### Sum
A `MathComponent` for `Σ`. It can take a `superScript` and/or `subScript` as arguments to add `MathComponents` (usually limits) on the top and bottom
@@ -315,6 +393,8 @@ const doc = new Document({
});
```
`MathSum` and `MathIntegral` take `limits`: `"aboveBelow"`, as a sum's limits usually are, or `"side"`, as an integral's usually are (`m:limLoc`). For other operators, such as ∏ and ⋃, see [Large operators](#large-operators).
### Radicals
A `MathComponent` for the `√` symbol. Examples include, square root, cube root etc. There is an optional `degree` parameter to specify the number of times the radicand is multiplied by itself. For example, `3` for cube root.
@@ -756,6 +836,228 @@ const doc = new Document({
});
```
### Large operators
`MathLargeOperator` writes a large operator with limits (`m:nary`), such as ∏, ⋃ or ∮, over what it applies to. `MathSum` and `MathIntegral` are two of these.
```ts live
import { Document, Paragraph } from "docx";
import { Math, MathLargeOperator, MathRun } from "docx/math";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
new Math({
children: [
new MathLargeOperator({
operator: "product",
subScript: [new MathRun("i=1")],
superScript: [new MathRun("n")],
children: [new MathRun("i")],
}),
new MathLargeOperator({
operator: "contourIntegral",
subScript: [new MathRun("C")],
children: [new MathRun("F⋅dr")],
}),
],
}),
],
}),
],
},
],
});
```
| Option | Type | Default | Notes |
| ------------- | ------------------------ | ----------------------------------------------- | -------------------------------- |
| `operator` | See below | | |
| `children` | `MathComponent[]` | | What the operator applies to |
| `subScript` | `MathComponent[]` | | The lower limit |
| `superScript` | `MathComponent[]` | | The upper limit |
| `limits` | `"aboveBelow"`, `"side"` | `"side"` for integrals, and `"aboveBelow"` else | Where the limits go (`m:limLoc`) |
The operators, with LaTeX's names for them:
| `operator` | Operator | LaTeX |
| --------------------------------------------------------------------------- | -------- | ---------------------------------------------- |
| `"sum"`, `"product"`, `"coproduct"` | ∑ ∏ ∐ | `\sum`, `\prod`, `\coprod` |
| `"union"`, `"intersection"`, `"squareUnion"`, `"multisetUnion"` | ⋃ ⋂ ⨆ ⨄ | `\bigcup`, `\bigcap`, `\bigsqcup`, `\biguplus` |
| `"logicalOr"`, `"logicalAnd"` | ⋁ ⋀ | `\bigvee`, `\bigwedge` |
| `"directSum"`, `"tensorProduct"`, `"circledDot"` | ⨁ ⨂ ⨀ | `\bigoplus`, `\bigotimes`, `\bigodot` |
| `"integral"`, `"doubleIntegral"`, `"tripleIntegral"`, `"quadrupleIntegral"` | ∫ ∬ ∭ ⨌ | `\int`, `\iint`, `\iiint`, `\iiiint` |
| `"contourIntegral"`, `"surfaceIntegral"`, `"volumeIntegral"` | ∮ ∯ ∰ | `\oint`, `\oiint`, `\oiiint` |
### Accents
`MathAccent` puts an accent over math (`m:acc`), which Word stretches over what it goes over:
```ts live
import { Document, Paragraph } from "docx";
import { Math, MathAccent, MathRun } from "docx/math";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
new Math({
children: [
new MathAccent({ accent: "hat", children: [new MathRun("x")] }),
new MathAccent({ accent: "rightArrow", children: [new MathRun("v")] }),
new MathAccent({ accent: "doubleDot", children: [new MathRun("x")] }),
],
}),
],
}),
],
},
],
});
```
`accent` is `"hat"` (the default, as `\hat`), `"check"`, `"tilde"`, `"acute"`, `"grave"`, `"dot"`, `"doubleDot"`, `"tripleDot"`, `"breve"`, `"bar"`, `"ring"`, `"rightArrow"` (as `\vec`), `"leftArrow"`, `"leftRightArrow"`, `"rightHarpoon"` or `"leftHarpoon"`.
### Bars
`MathBar` draws a line over or under math (`m:bar`), as long as what it goes over, as LaTeX's `\overline` and `\underline`:
```ts live
import { Document, Paragraph } from "docx";
import { Math, MathBar, MathRun } from "docx/math";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
new Math({
children: [
new MathBar({ children: [new MathRun("AB")] }),
new MathBar({ position: "below", children: [new MathRun("x")] }),
],
}),
],
}),
],
},
],
});
```
`position` is `"above"` (the default) or `"below"`.
### Braces
`MathBrace` draws a brace over or under math (`m:groupChr`), with a label on its other side, as LaTeX's `\overbrace` and `\underbrace`:
```ts live
import { Document, Paragraph } from "docx";
import { Math, MathBrace, MathRun } from "docx/math";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
new Math({
children: [
new MathBrace({
position: "below",
children: [new MathRun("1+2+⋯+n")],
label: [new MathRun({ text: "n terms", normalText: true })],
}),
],
}),
],
}),
],
},
],
});
```
| Option | Type | Default | Notes |
| ---------- | -------------------------------- | --------- | ----------------------------------------------------------------------------------- |
| `children` | `MathComponent[]` | | What the brace goes over or under |
| `position` | `"above"`, `"below"` | `"above"` | |
| `brace` | `"curly"`, `"square"`, `"round"` | `"curly"` | ⏞ ⏟, ⎴ ⎵ and ⏜ ⏝ |
| `label` | `MathComponent[]` | | On the brace's other side, in a limit (`m:limUpp` or `m:limLow`), as Word writes it |
### Boxes
`MathBox` draws a box around math (`m:borderBox`), as LaTeX's `\boxed`, or lines struck through it, as `\cancel`:
```ts live
import { Document, Paragraph } from "docx";
import { Math, MathBox, MathRun } from "docx/math";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
new Math({
children: [
new MathBox({ children: [new MathRun("E=mc²")] }),
new MathBox({ borders: [], strikes: ["diagonalUp"], children: [new MathRun("x")] }),
],
}),
],
}),
],
},
],
});
```
| Option | Type | Default | Notes |
| ---------- | ------------------------------------------------------------------------ | ------------------------------------ | ----------------------------------------------------------------------------- |
| `children` | `MathComponent[]` | | |
| `borders` | A list of `"top"`, `"bottom"`, `"left"`, `"right"` | `["top", "bottom", "left", "right"]` | The sides drawn. `[]` draws none, for lines struck through with no box |
| `strikes` | A list of `"horizontal"`, `"vertical"`, `"diagonalUp"`, `"diagonalDown"` | `[]` | `"diagonalUp"` is `\cancel`, `"diagonalDown"` `\bcancel`, and both `\xcancel` |
### Phantoms
`MathPhantom` writes math that takes up room without being seen (`m:phant`), as LaTeX's `\phantom`, to leave space for it or line things up with it. Or math that is seen but takes up less room, as `\smash`:
```ts live
import { Document, Paragraph } from "docx";
import { Math, MathPhantom, MathRun } from "docx/math";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
new Math({
children: [new MathRun("a"), new MathPhantom({ children: [new MathRun("+b")] }), new MathRun("+c")],
}),
],
}),
],
},
],
});
```
| Option | Type | Default | Notes |
| ---------- | ----------------- | ------- | ------------------------------------------------------------------- |
| `children` | `MathComponent[]` | | |
| `visible` | `boolean` | `false` | Whether the math is seen (`m:show`) |
| `width` | `boolean` | `true` | Whether it takes up its width. `false` as `\vphantom` (`m:zeroWid`) |
| `height` | `boolean` | `true` | Whether it takes up its height above the line (`m:zeroAsc`) |
| `depth` | `boolean` | `true` | Whether it takes up its depth below the line (`m:zeroDesc`) |
### Matrices
`MathMatrix` writes a matrix (`m:m`): rows of cells, each cell a list of `MathComponents`, in brackets or none. A row shorter than the longest gets empty cells at its end.
@@ -935,6 +1237,8 @@ const doc = new Document({
## From LaTeX
`latexToMath` turns LaTeX into these components: see [Math from LaTeX](usage/math-latex.md). By hand, LaTeX's environments and commands are these:
| LaTeX | `docx/math` |
| --------------------------------------- | ---------------------------------------------------------------------- |
| `\begin{matrix}` | `new MathMatrix({ rows })` |
@@ -950,6 +1254,14 @@ const doc = new Document({
| `\left\| x \right\|`, `\lVert v \rVert` | `new MathBrackets({ open: "\|", close: "\|", children })`, `open: "‖"` |
| `\langle a \mid b \rangle` | `new MathBrackets({ open: "⟨", close: "⟩", separator: "\|", items })` |
| `\text{if}` | `new MathRun({ text: "if", normalText: true })` |
| `\mathbb{R}`, `\mathbf{F}` | `new MathRun({ text: "R", script: "doubleStruck" })`, `style: "bold"` |
| `\prod`, `\bigcup`, `\oint` | `new MathLargeOperator({ operator: "product", children })` |
| `\hat{x}`, `\vec{v}` | `new MathAccent({ accent: "hat", children })` |
| `\overline{AB}` | `new MathBar({ children })` |
| `\underbrace{…}_{n}` | `new MathBrace({ position: "below", children, label })` |
| `\boxed{…}`, `\cancel{…}` | `new MathBox({ children })`, `borders: [], strikes: ["diagonalUp"]` |
| `\phantom{…}` | `new MathPhantom({ children })` |
| `\binom{n}{k}` | `MathFraction` with `type: "noBar"` in `MathRoundBrackets` |
## Compatibility
@@ -958,6 +1270,8 @@ Word is the reference. Other applications differ:
- **LibreOffice** centres every column of a matrix, centres the rows of an equation array without lining them up, and shows the `&` between parts and the `#` before equation numbers.
- **Pages** centres every column of a matrix and shows the `#` before equation numbers.
- **Word 2013 and older** show the `#` before equation numbers.
- **LibreOffice** draws only ∑, ∏, ∐ and the integrals as large operators, and draws `¿` for others, such as ⋃. Of the alphabets, it draws only double-struck letters, and of the styles none. It doesn't draw boxes or lines struck through.
- **Pages** doesn't draw a box's sides.
## Demo
@@ -970,3 +1284,9 @@ Matrices, equations lined up with numbers, cases, and brackets of any characters
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/math/matrices-and-alignment.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/math/matrices-and-alignment.ts_
Math from LaTeX:
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/math/latex.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/math/latex.ts_
+1 -1
View File
@@ -22,7 +22,7 @@ OUT="${1:-build/shape-demos}"
shift || true
DEMOS=("$@")
if [ ${#DEMOS[@]} -eq 0 ]; then
DEMOS=(shapes/inline-shapes shapes/shapes shapes/shape-groups shapes/shape-connectors shapes/shape-styles shapes/shape-diagrams shapes/shape-layout shapes/shape-document-styles shapes/shape-swimlanes shapes/shape-page-layout styles/theme shapes/custom-shapes charts/charts charts/chart-options charts/charts-in-templates charts/chart-data-in-templates charts/more-charts math/matrices-and-alignment)
DEMOS=(shapes/inline-shapes shapes/shapes shapes/shape-groups shapes/shape-connectors shapes/shape-styles shapes/shape-diagrams shapes/shape-layout shapes/shape-document-styles shapes/shape-swimlanes shapes/shape-page-layout styles/theme shapes/custom-shapes charts/charts charts/chart-options charts/charts-in-templates charts/chart-data-in-templates charts/more-charts math/matrices-and-alignment math/latex)
fi
SOFFICE="${SOFFICE:-soffice}"
Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

@@ -40,5 +40,28 @@ describe("MathFraction", () => {
],
});
});
it.each([
["stacked", "bar"],
["skewed", "skw"],
["linear", "lin"],
["noBar", "noBar"],
] as const)("writes a %s fraction with m:type %s", (type, value) => {
const tree = new Formatter().format(new MathFraction({ numerator: [new MathRun("a")], denominator: [new MathRun("b")], type }));
expect(tree).to.deep.equal({
"m:f": [
{ "m:fPr": [{ "m:type": { _attr: { "m:val": value } } }] },
{ "m:num": [{ "m:r": [{ "m:t": ["a"] }] }] },
{ "m:den": [{ "m:r": [{ "m:t": ["b"] }] }] },
],
});
});
it("throws for a type it doesn't know, for code that isn't type checked", () => {
// @ts-expect-error -- not a type
expect(() => new MathFraction({ numerator: [], denominator: [], type: "lin" })).toThrow(
'MathFraction: type is "lin", which isn\'t one of stacked, skewed, linear, noBar',
);
});
});
});
@@ -7,12 +7,24 @@
*
* @module
*/
import { XmlComponent } from "@file/xml-components";
import { BuilderElement, XmlComponent } from "@file/xml-components";
import type { MathComponent } from "../math-component";
import { MathDenominator } from "./math-denominator";
import { MathNumerator } from "./math-numerator";
/**
* How a fraction is drawn (`m:type`):
*
* - `"stacked"`: the numerator over the denominator, with a bar between them;
* - `"skewed"`: the numerator up and to the left of a slash, and the denominator down and to the right, as ½;
* - `"linear"`: on one line, with a slash between them, as a/b;
* - `"noBar"`: stacked, with no bar between them, as in a binomial coefficient.
*/
export type MathFractionType = "stacked" | "skewed" | "linear" | "noBar";
const TYPES: Readonly<Record<MathFractionType, string>> = { stacked: "bar", skewed: "skw", linear: "lin", noBar: "noBar" };
/**
* Options for creating a MathFraction.
*
@@ -23,6 +35,11 @@ export type IMathFractionOptions = {
readonly numerator: readonly MathComponent[];
/** Math components for the denominator (bottom) of the fraction */
readonly denominator: readonly MathComponent[];
/**
* How the fraction is drawn: stacked, skewed, linear, or stacked with no bar.
* @default "stacked"
*/
readonly type?: MathFractionType;
};
/**
@@ -51,12 +68,34 @@ export type IMathFractionOptions = {
* numerator: [new MathRun("a + b")],
* denominator: [new MathRun("c")],
* });
*
* // n over k, as a binomial coefficient, in brackets
* new MathRoundBrackets({
* children: [new MathFraction({ numerator: [new MathRun("n")], denominator: [new MathRun("k")], type: "noBar" })],
* });
* ```
*/
export class MathFraction extends XmlComponent {
public constructor(options: IMathFractionOptions) {
super("m:f");
if (options.type !== undefined) {
if (!Object.keys(TYPES).includes(options.type)) {
throw new Error(`MathFraction: type is "${options.type}", which isn't one of ${Object.keys(TYPES).join(", ")}`);
}
this.root.push(
new BuilderElement({
name: "m:fPr",
children: [
new BuilderElement<{ readonly value: string }>({
name: "m:type",
attributes: { value: { key: "m:val", value: TYPES[options.type] } },
}),
],
}),
);
}
this.root.push(new MathNumerator(options.numerator));
this.root.push(new MathDenominator(options.denominator));
}
+81
View File
@@ -29,5 +29,86 @@ describe("MathRun", () => {
"m:r": [{ "m:rPr": [{ "m:nor": { _attr: { "m:val": 1 } } }] }, { "m:t": [{ _attr: { "xml:space": "preserve" } }, "if "] }],
});
});
it("writes a style and an alphabet with m:sty and m:scr, the alphabet first", () => {
expect(new Formatter().format(new MathRun({ text: "R", style: "plain", script: "doubleStruck" }))).to.deep.equal({
"m:r": [
{ "m:rPr": [{ "m:scr": { _attr: { "m:val": "double-struck" } } }, { "m:sty": { _attr: { "m:val": "p" } } }] },
{ "m:t": ["R"] },
],
});
});
it.each([
["plain", "p"],
["bold", "b"],
["italic", "i"],
["boldItalic", "bi"],
] as const)("writes the %s style as %s", (style, value) => {
expect(new Formatter().format(new MathRun({ text: "x", style }))).to.deep.equal({
"m:r": [{ "m:rPr": [{ "m:sty": { _attr: { "m:val": value } } }] }, { "m:t": ["x"] }],
});
});
it.each([
["script", "script"],
["fraktur", "fraktur"],
["doubleStruck", "double-struck"],
["sansSerif", "sans-serif"],
["monospace", "monospace"],
] as const)("writes the %s alphabet as %s, upright unless given a style, as LaTeX draws it", (script, value) => {
expect(new Formatter().format(new MathRun({ text: "A", script }))).to.deep.equal({
"m:r": [
{ "m:rPr": [{ "m:scr": { _attr: { "m:val": value } } }, { "m:sty": { _attr: { "m:val": "p" } } }] },
{ "m:t": ["A"] },
],
});
});
it("writes the roman alphabet with no style, leaving Word's italic letters", () => {
expect(new Formatter().format(new MathRun({ text: "A", script: "roman" }))).to.deep.equal({
"m:r": [{ "m:rPr": [{ "m:scr": { _attr: { "m:val": "roman" } } }] }, { "m:t": ["A"] }],
});
});
it("keeps a style given with an alphabet, such as italic sans-serif", () => {
expect(new Formatter().format(new MathRun({ text: "A", script: "sansSerif", style: "italic" }))).to.deep.equal({
"m:r": [
{ "m:rPr": [{ "m:scr": { _attr: { "m:val": "sans-serif" } } }, { "m:sty": { _attr: { "m:val": "i" } } }] },
{ "m:t": ["A"] },
],
});
});
it("writes literal text with m:lit, before normal text", () => {
expect(new Formatter().format(new MathRun({ text: "&", literal: true, normalText: true }))).to.deep.equal({
"m:r": [{ "m:rPr": [{ "m:lit": { _attr: { "m:val": 1 } } }, { "m:nor": { _attr: { "m:val": 1 } } }] }, { "m:t": ["&"] }],
});
expect(new Formatter().format(new MathRun({ text: "&", literal: true, style: "bold" }))).to.deep.equal({
"m:r": [{ "m:rPr": [{ "m:lit": { _attr: { "m:val": 1 } } }, { "m:sty": { _attr: { "m:val": "b" } } }] }, { "m:t": ["&"] }],
});
});
it("throws for normal text with a style or an alphabet, which the schema doesn't allow together", () => {
expect(() => new MathRun({ text: "if", normalText: true, style: "bold" })).toThrow(
"MathRun: normalText can't be given with style or script",
);
expect(() => new MathRun({ text: "if", normalText: true, script: "script" })).toThrow(
"MathRun: normalText can't be given with style or script",
);
});
it("throws for a style or an alphabet it doesn't know, for code that isn't type checked", () => {
// @ts-expect-error -- not a style
expect(() => new MathRun({ text: "x", style: "p" })).toThrow(
'MathRun: style is "p", which isn\'t one of plain, bold, italic, boldItalic',
);
// @ts-expect-error -- not a style, though every object has it
expect(() => new MathRun({ text: "x", style: "toString" })).toThrow('MathRun: style is "toString"');
// @ts-expect-error -- not an alphabet
expect(() => new MathRun({ text: "x", script: "double-struck" })).toThrow(
'MathRun: script is "double-struck", which isn\'t one of roman, script, fraktur, doubleStruck, sansSerif, monospace',
);
});
});
});
+82 -11
View File
@@ -7,10 +7,36 @@
*
* @module
*/
// cspell:ignore mathbb mathbf mathfrak mathrm mathsf mathtt
import { BuilderElement, XmlComponent } from "@file/xml-components";
import { MathText } from "./math-text";
/**
* How a {@link MathRun}'s letters are drawn (`m:sty`):
*
* - `"plain"`: upright, as LaTeX's `\mathrm`;
* - `"bold"`: bold and upright, as `\mathbf`;
* - `"italic"`: italic, as `\mathit`;
* - `"boldItalic"`: bold and italic, as `\boldsymbol`.
*
* Word draws letters in italic, and digits and capital Greek letters upright, unless a run has a style. A run in an
* alphabet other than roman is plain unless given a style, as LaTeX draws its alphabets upright.
*/
export type MathRunStyle = "plain" | "bold" | "italic" | "boldItalic";
/**
* The alphabet a {@link MathRun}'s letters are drawn in (`m:scr`):
*
* - `"roman"`: the math font's own letters, as Word draws them unless a run has an alphabet;
* - `"script"`: 𝒜, as LaTeX's `\mathcal` and `\mathscr`;
* - `"fraktur"`: 𝔄, as `\mathfrak`;
* - `"doubleStruck"`: 𝔸, as `\mathbb`, for sets such as ℝ;
* - `"sansSerif"`: 𝖠, as `\mathsf`;
* - `"monospace"`: 𝙰, as `\mathtt`.
*/
export type MathRunScript = "roman" | "script" | "fraktur" | "doubleStruck" | "sansSerif" | "monospace";
/**
* Options for a {@link MathRun}.
*/
@@ -19,12 +45,43 @@ export type MathRunOptions = {
readonly text: string;
/**
* Writes the text as ordinary text rather than math, as Word's "Normal Text" button does (`m:nor`): upright and in
* the document's font, with its spaces kept. For words in an equation, such as "if" and "otherwise" in cases.
* the document's font, with its spaces kept. For words in an equation, such as "if" and "otherwise" in cases. It
* can't be given with `style` or `script`, which are for math.
* @default false
*/
readonly normalText?: boolean;
/**
* How the letters are drawn: plain (upright), bold, italic or both (`m:sty`).
* @default "plain" with a `script` other than roman, as LaTeX draws its alphabets upright; otherwise none, and Word
* draws letters in italic
*/
readonly style?: MathRunStyle;
/**
* The alphabet the letters are drawn in, such as double-struck for ℝ (`m:scr`).
*/
readonly script?: MathRunScript;
/**
* Takes the text as it is (`m:lit`), rather than as something Word builds up or lines up, such as an `&` in a
* `MathEquationArray`, which would otherwise be a point the rows line up at.
* @default false
*/
readonly literal?: boolean;
};
const STYLES: Readonly<Record<MathRunStyle, string>> = { plain: "p", bold: "b", italic: "i", boldItalic: "bi" };
const SCRIPTS: Readonly<Record<MathRunScript, string>> = {
roman: "roman",
script: "script",
fraktur: "fraktur",
doubleStruck: "double-struck",
sansSerif: "sans-serif",
monospace: "monospace",
};
const createValueElement = (name: string, value: string | number): XmlComponent =>
new BuilderElement<{ readonly value: string | number }>({ name, attributes: { value: { key: "m:val", value } } });
/**
* Represents a run of text within a math equation.
*
@@ -53,23 +110,37 @@ export type MathRunOptions = {
* ```typescript
* new MathRun("x + y");
* new MathRun({ text: "if ", normalText: true });
* new MathRun({ text: "R", script: "doubleStruck" });
* new MathRun({ text: "d", style: "plain" });
* ```
*/
export class MathRun extends XmlComponent {
public constructor(options: string | MathRunOptions) {
super("m:r");
const { text, normalText } = typeof options === "string" ? { text: options, normalText: false } : options;
const { text, normalText, script, literal, ...rest } = typeof options === "string" ? { text: options } : options;
// Word draws a run with no style in italic, even in another alphabet, which would make sansSerif italic
const style = rest.style ?? (script === undefined || script === "roman" ? undefined : "plain");
if (normalText) {
this.root.push(
new BuilderElement({
name: "m:rPr",
children: [
new BuilderElement<{ readonly on: number }>({ name: "m:nor", attributes: { on: { key: "m:val", value: 1 } } }),
],
}),
);
if (normalText && (style !== undefined || script !== undefined)) {
throw new Error("MathRun: normalText can't be given with style or script, which are for math. Give one or the other");
}
if (style !== undefined && !Object.keys(STYLES).includes(style)) {
throw new Error(`MathRun: style is "${style}", which isn't one of ${Object.keys(STYLES).join(", ")}`);
}
if (script !== undefined && !Object.keys(SCRIPTS).includes(script)) {
throw new Error(`MathRun: script is "${script}", which isn't one of ${Object.keys(SCRIPTS).join(", ")}`);
}
// In the schema's order: m:lit, then m:nor or m:scr and m:sty
const properties = [
...(literal ? [createValueElement("m:lit", 1)] : []),
...(normalText ? [createValueElement("m:nor", 1)] : []),
...(script === undefined ? [] : [createValueElement("m:scr", SCRIPTS[script])]),
...(style === undefined ? [] : [createValueElement("m:sty", STYLES[style])]),
];
if (properties.length > 0) {
this.root.push(new BuilderElement({ name: "m:rPr", children: properties }));
}
this.root.push(new MathText(text));
@@ -0,0 +1,23 @@
/**
* The value of `m:limLoc` for a {@link MathLimitsPosition}. Internal: not exported from docx.
*
* @module
*/
import type { MathLimitsPosition } from "./math-limit-location";
const LOCATIONS: Readonly<Record<MathLimitsPosition, string>> = { aboveBelow: "undOvr", side: "subSup" };
/**
* The value of `m:limLoc` for where limits go, or the default when none is given.
*
* @throws If the position isn't one of those allowed, for code that isn't type checked
*/
export const limitLocationValue = (owner: string, limits: MathLimitsPosition | undefined, defaultValue: string): string => {
if (limits === undefined) {
return defaultValue;
}
if (!Object.keys(LOCATIONS).includes(limits)) {
throw new Error(`${owner}: limits is "${limits}", which isn't one of ${Object.keys(LOCATIONS).join(", ")}`);
}
return LOCATIONS[limits];
};
@@ -118,5 +118,20 @@ describe("MathIntegral", () => {
],
});
});
it.each([
["aboveBelow", "undOvr"],
["side", "subSup"],
] as const)("puts the limits %s with m:limLoc %s", (limits, value) => {
const tree = new Formatter().format(new MathIntegral({ children: [new MathRun("x")], subScript: [new MathRun("a")], limits }));
expect(tree["m:nary"][0]["m:naryPr"]).toContainEqual({ "m:limLoc": { _attr: { "m:val": value } } });
});
it("throws for limits it doesn't know, for code that isn't type checked", () => {
// @ts-expect-error -- not a position
expect(() => new MathIntegral({ children: [], limits: "undOvr" })).toThrow(
'MathIntegral: limits is "undOvr", which isn\'t one of aboveBelow, side',
);
});
});
});
@@ -10,7 +10,9 @@
import { XmlComponent } from "@file/xml-components";
import type { MathComponent } from "../math-component";
import { limitLocationValue } from "./limit-location-value";
import { createMathBase } from "./math-base";
import type { MathLimitsPosition } from "./math-limit-location";
import { createMathNAryProperties } from "./math-n-ary-properties";
import { createMathSubScriptElement } from "./math-sub-script";
import { createMathSuperScriptElement } from "./math-super-script";
@@ -27,6 +29,11 @@ export type IMathIntegralOptions = {
readonly subScript?: readonly MathComponent[];
/** Optional upper bound of integration */
readonly superScript?: readonly MathComponent[];
/**
* Where the limits go: above and below the ∫, or to its right.
* @default "side"
*/
readonly limits?: MathLimitsPosition;
};
/**
@@ -69,7 +76,7 @@ export class MathIntegral extends XmlComponent {
accent: "",
hasSuperScript: !!options.superScript,
hasSubScript: !!options.subScript,
limitLocationVal: "subSup",
limitLocationVal: limitLocationValue("MathIntegral", options.limits, "subSup"),
}),
);
@@ -9,6 +9,14 @@
*/
import { BuilderElement, type XmlComponent } from "@file/xml-components";
/**
* Where a large operator's limits go (`m:limLoc`):
*
* - `"aboveBelow"`: above and below it, as a sum's usually are;
* - `"side"`: to its right, as a superscript and subscript, as an integral's usually are.
*/
export type MathLimitsPosition = "aboveBelow" | "side";
/**
* Options for creating a limit location element.
*/
@@ -155,5 +155,20 @@ describe("MathSum", () => {
],
});
});
it.each([
["aboveBelow", "undOvr"],
["side", "subSup"],
] as const)("puts the limits %s with m:limLoc %s", (limits, value) => {
const tree = new Formatter().format(new MathSum({ children: [new MathRun("x")], subScript: [new MathRun("a")], limits }));
expect(tree["m:nary"][0]["m:naryPr"]).toContainEqual({ "m:limLoc": { _attr: { "m:val": value } } });
});
it("throws for limits it doesn't know, for code that isn't type checked", () => {
// @ts-expect-error -- not a position
expect(() => new MathSum({ children: [], limits: "undOvr" })).toThrow(
'MathSum: limits is "undOvr", which isn\'t one of aboveBelow, side',
);
});
});
});
@@ -10,7 +10,9 @@
import { XmlComponent } from "@file/xml-components";
import type { MathComponent } from "../math-component";
import { limitLocationValue } from "./limit-location-value";
import { createMathBase } from "./math-base";
import type { MathLimitsPosition } from "./math-limit-location";
import { createMathNAryProperties } from "./math-n-ary-properties";
import { createMathSubScriptElement } from "./math-sub-script";
import { createMathSuperScriptElement } from "./math-super-script";
@@ -27,6 +29,11 @@ export type IMathSumOptions = {
readonly subScript?: readonly MathComponent[];
/** Optional upper bound (superscript) of the sum */
readonly superScript?: readonly MathComponent[];
/**
* Where the limits go: above and below the ∑, or to its right.
* @default "aboveBelow"
*/
readonly limits?: MathLimitsPosition;
};
/**
@@ -69,6 +76,7 @@ export class MathSum extends XmlComponent {
accent: "∑",
hasSuperScript: !!options.superScript,
hasSubScript: !!options.subScript,
limitLocationVal: limitLocationValue("MathSum", options.limits, "undOvr"),
}),
);
+21 -2
View File
@@ -5,8 +5,20 @@ import * as docx from "docx";
import * as math from ".";
// docx/math's own components, which docx doesn't export
const OWN = ["MathBrackets", "MathCases", "MathEquationArray", "MathMatrix"];
// docx/math's own components and functions, which docx doesn't export
const OWN = [
"MathAccent",
"MathBar",
"MathBox",
"MathBrace",
"MathBrackets",
"MathCases",
"MathEquationArray",
"MathLargeOperator",
"MathMatrix",
"MathPhantom",
"latexToMath",
];
describe("docx/math", () => {
it("exports docx's own math classes and functions, not copies of them", () => {
@@ -34,6 +46,13 @@ describe("docx/math", () => {
expectTypeOf<math.MathBrackets>().toExtend<docx.MathComponent>();
expectTypeOf<math.MathCases>().toExtend<docx.MathComponent>();
expectTypeOf<math.MathEquationArray>().toExtend<docx.MathComponent>();
expectTypeOf<math.MathAccent>().toExtend<docx.MathComponent>();
expectTypeOf<math.MathBar>().toExtend<docx.MathComponent>();
expectTypeOf<math.MathBox>().toExtend<docx.MathComponent>();
expectTypeOf<math.MathBrace>().toExtend<docx.MathComponent>();
expectTypeOf<math.MathLargeOperator>().toExtend<docx.MathComponent>();
expectTypeOf<math.MathPhantom>().toExtend<docx.MathComponent>();
expectTypeOf(math.latexToMath).returns.toExtend<docx.IMathOptions["children"]>();
expectTypeOf<docx.Math>().toExtend<docx.ParagraphChild>();
const paragraph = new docx.Paragraph({
+16 -3
View File
@@ -1,10 +1,12 @@
/**
* Math for docx documents: equations, such as fractions, sums, integrals, radicals, scripts, brackets, matrices, cases
* and aligned equations with numbers, written as Office Math, which Word shows and edits as equations.
* Math for docx documents: equations, such as fractions, sums, integrals and other large operators, radicals, scripts,
* brackets, accents, braces, boxes, matrices, cases and aligned equations with numbers, written as Office Math, which
* Word shows and edits as equations. `latexToMath` turns LaTeX into the same math.
*
* Math comes with the `docx` package, from `docx/math`. Everything else, such as the document and its paragraphs,
* comes from `docx`. `docx` still exports the math it had before `docx/math`, as the same classes, not copies, so the
* two can be mixed. Matrices, cases, equation arrays and brackets of any characters come from `docx/math` only.
* two can be mixed. Matrices, cases, equation arrays, brackets of any characters, accents, bars, braces, boxes,
* phantoms, large operators and `latexToMath` come from `docx/math` only.
*
* @module
*
@@ -85,11 +87,20 @@ export type {
IMathSumOptions,
IMathSuperScriptOptions,
MathComponent,
MathFractionType,
MathLimitsPosition,
MathRunOptions,
MathRunScript,
MathRunStyle,
} from "docx";
export { MathAccent, type MathAccentName, type MathAccentOptions } from "./math-accent";
export { MathBar, type MathBarOptions, type MathPosition } from "./math-bar";
export { MathBox, type MathBoxOptions, type MathBoxSide, type MathBoxStrike } from "./math-box";
export { MathBrace, type MathBraceOptions, type MathBraceShape } from "./math-brace";
export { MathBrackets, type MathBracketsOptions } from "./math-brackets";
export { MathCases, type MathCase, type MathCasesOptions } from "./math-cases";
export { MathEquationArray, type MathEquationArrayOptions, type MathEquationArrayRow } from "./math-equation-array";
export { MathLargeOperator, type MathLargeOperatorName, type MathLargeOperatorOptions } from "./math-large-operator";
export {
MathMatrix,
type MathColumnAlignment,
@@ -97,3 +108,5 @@ export {
type MathMatrixOptions,
type MathVerticalAlignment,
} from "./math-matrix";
export { MathPhantom, type MathPhantomOptions } from "./math-phantom";
export { latexToMath } from "./latex-to-math";
+978
View File
@@ -0,0 +1,978 @@
import { describe, expect, it } from "vitest";
import xml from "xml";
import { Formatter } from "@export/formatter";
import {
Math,
type MathComponent,
MathFraction,
MathFunction,
MathLimitLower,
MathLimitUpper,
MathRadical,
MathRun,
type MathRunOptions,
MathSubScript,
MathSubSuperScript,
MathSuperScript,
} from "docx";
import { latexToMath } from "./latex-to-math";
import { MathAccent } from "./math-accent";
import { MathBar } from "./math-bar";
import { MathBox } from "./math-box";
import { MathBrace } from "./math-brace";
import { MathBrackets } from "./math-brackets";
import { MathCases } from "./math-cases";
import { MathEquationArray } from "./math-equation-array";
import { MathLargeOperator } from "./math-large-operator";
import { MathMatrix } from "./math-matrix";
import { MathPhantom } from "./math-phantom";
const written = (...children: readonly MathComponent[]): string => xml(new Formatter().format(new Math({ children })));
/** The math the LaTeX is read as, written, to compare with the same math built by hand */
const read = (latex: string): string => written(...latexToMath(latex));
const run = (text: string, options: Omit<MathRunOptions, "text"> = {}): MathRun => new MathRun({ text, ...options });
const plain = (text: string): MathRun => run(text, { style: "plain" });
const words = (text: string): MathRun => run(text, { normalText: true });
const space = (): MathRun => new MathRun("\u200B");
const fn = (name: string, ...children: readonly MathComponent[]): MathFunction => new MathFunction({ name: [plain(name)], children });
describe("latexToMath", () => {
describe("text and symbols", () => {
it("joins letters, digits and operators in one run, with a minus sign for a hyphen, as LaTeX draws it", () => {
expect(read("a + 2b - c * d")).toBe(written(run("a+2b−c∗d")));
});
it("leaves out spaces, and comments", () => {
expect(read("a b % a comment\n c")).toBe(written(run("abc")));
});
it("writes Greek letters, with capitals upright as LaTeX draws them, and italic ones for \\varGamma", () => {
expect(read("\\alpha\\varepsilon\\phi\\varphi \\Gamma \\varDelta")).toBe(
written(run("αεϕφ"), plain("Γ"), run("Δ", { style: "italic" })),
);
});
it("keeps the font it is in for capital Greek letters", () => {
expect(read("\\mathbf{\\Omega}")).toBe(written(run("Ω", { style: "bold" })));
expect(read("\\mathbf{\\varOmega}")).toBe(written(run("Ω", { style: "bold" })));
});
it("writes symbols, relations and arrows", () => {
expect(
read(
"\\infty \\le \\ne \\in \\to \\Rightarrow \\times \\cdot \\pm \\ldots \\cdots \\{ \\} \\| \\langle \\rangle \\backslash",
),
).toBe(written(run("∞≤≠∈→⇒×⋅±…⋯{}‖⟨⟩\\")));
});
it("takes characters typed as they are", () => {
expect(read("α ≤ β")).toBe(written(run("α≤β")));
});
it("writes spaces as spaces of their width, and leaves out negative ones", () => {
expect(read("a\\,b\\:c\\;d\\quad e\\qquad f\\!g~h\\ i\\enspace j")).toBe(
written(run("a\u2009b\u2005c\u2004d\u2003e\u2003\u2003fg\u00A0h\u2004i\u2002j")),
);
});
it("writes \\& and \\# literally, so an equation array doesn't take them as a point or a number", () => {
expect(read("a \\& b \\# c")).toBe(
written(run("a"), run("&", { literal: true }), run("b"), run("#", { literal: true }), run("c")),
);
});
it("writes escaped characters", () => {
expect(read("\\% \\$ \\_")).toBe(written(run("%$_")));
});
it("writes a relation with a line through it for \\not", () => {
expect(read("a \\not= b \\not\\in C \\not< d \\not\\perp e \\not| f")).toBe(written(run("a≠b∉C≮d⊥\u0338e|\u0338f")));
});
it("writes a colon as a relation, and a tilde as a space that doesn't break", () => {
expect(read("f\\colon A \\to B")).toBe(written(run("f:A→B")));
});
});
describe("scripts", () => {
it("writes a superscript, a subscript and both, in either order", () => {
expect(read("x^2")).toBe(written(new MathSuperScript({ children: [run("x")], superScript: [run("2")] })));
expect(read("x_i")).toBe(written(new MathSubScript({ children: [run("x")], subScript: [run("i")] })));
const both = written(new MathSubSuperScript({ children: [run("x")], subScript: [run("i")], superScript: [run("2")] }));
expect(read("x_i^2")).toBe(both);
expect(read("x^2_i")).toBe(both);
});
it("puts a script on the letter before it only, and on a group in braces", () => {
expect(read("ab^2")).toBe(written(run("a"), new MathSuperScript({ children: [run("b")], superScript: [run("2")] })));
expect(read("{a+b}^2")).toBe(written(new MathSuperScript({ children: [run("a+b")], superScript: [run("2")] })));
});
it("reads a number as one base, but a script of one token as its first character, as LaTeX does", () => {
expect(read("10.5^{-3}")).toBe(written(new MathSuperScript({ children: [run("10.5")], superScript: [run("−3")] })));
expect(read("x^12")).toBe(written(new MathSuperScript({ children: [run("x")], superScript: [run("1")] }), run("2")));
});
it("writes a script of a command that writes nothing with a zero-width space", () => {
expect(read("x^\\!")).toBe(written(new MathSuperScript({ children: [run("x")], superScript: [space()] })));
});
it("takes a command and its arguments as a script", () => {
expect(read("e^\\alpha")).toBe(written(new MathSuperScript({ children: [run("e")], superScript: [run("α")] })));
expect(read("x^\\frac12")).toBe(
written(
new MathSuperScript({
children: [run("x")],
superScript: [new MathFraction({ numerator: [run("1")], denominator: [run("2")] })],
}),
),
);
});
it("writes primes as a superscript, before any other", () => {
expect(read("f'")).toBe(written(new MathSuperScript({ children: [run("f")], superScript: [run("′")] })));
expect(read("f''")).toBe(written(new MathSuperScript({ children: [run("f")], superScript: [run("″")] })));
expect(read("f'''")).toBe(written(new MathSuperScript({ children: [run("f")], superScript: [run("‴")] })));
expect(read("f''''")).toBe(written(new MathSuperScript({ children: [run("f")], superScript: [run("⁗")] })));
expect(read("f'''''")).toBe(written(new MathSuperScript({ children: [run("f")], superScript: [run("′′′′′")] })));
expect(read("f'^2")).toBe(written(new MathSuperScript({ children: [run("f")], superScript: [run("′2")] })));
});
it("puts scripts with nothing before them on an empty base, as for an isotope", () => {
expect(read("{}^{14}_{6}C")).toBe(
written(new MathSubSuperScript({ children: [space()], subScript: [run("6")], superScript: [run("14")] }), run("C")),
);
expect(read("^2")).toBe(written(new MathSuperScript({ children: [space()], superScript: [run("2")] })));
expect(read("'")).toBe(written(new MathSuperScript({ children: [space()], superScript: [run("′")] })));
});
it("writes an empty script with a zero-width space", () => {
expect(read("x^{}")).toBe(written(new MathSuperScript({ children: [run("x")], superScript: [space()] })));
});
it("throws for two superscripts or subscripts in a row, or a prime after a superscript", () => {
expect(() => latexToMath("x^a^b")).toThrow(
"latexToMath: there are two superscripts in a row. Put them in braces, as in x^{ab}, at character 4",
);
expect(() => latexToMath("x_a_b")).toThrow("there are two subscripts in a row");
expect(() => latexToMath("x^2'")).toThrow("a prime follows a superscript");
});
it("throws for a script with nothing to raise", () => {
expect(() => latexToMath("x^")).toThrow("^ needs an argument");
expect(() => latexToMath("x^_2")).toThrow("^ needs an argument");
expect(() => latexToMath("{x^}")).toThrow("^ needs an argument");
});
});
describe("fractions and roots", () => {
const fraction = new MathFraction({ numerator: [run("a")], denominator: [run("b")] });
it("writes \\frac and its kinds as fractions", () => {
for (const latex of ["\\frac{a}{b}", "\\dfrac ab", "\\tfrac{a}{b}", "\\cfrac[l]{a}{b}", "{a \\over b}", "a \\over b"]) {
expect(read(latex), latex).toBe(written(fraction));
}
});
it("writes an empty numerator or denominator with a zero-width space", () => {
expect(read("\\frac{}{}")).toBe(written(new MathFraction({ numerator: [space()], denominator: [space()] })));
});
it("writes \\nicefrac and \\sfrac as skewed fractions", () => {
const skewed = written(new MathFraction({ numerator: [run("1")], denominator: [run("2")], type: "skewed" }));
expect(read("\\nicefrac{1}{2}")).toBe(skewed);
expect(read("\\sfrac12")).toBe(skewed);
});
it("writes binomial coefficients as fractions without a bar, in round brackets", () => {
const binomial = written(
new MathBrackets({ children: [new MathFraction({ numerator: [run("n")], denominator: [run("k")], type: "noBar" })] }),
);
for (const latex of ["\\binom{n}{k}", "\\dbinom nk", "\\tbinom{n}{k}", "{n \\choose k}"]) {
expect(read(latex), latex).toBe(binomial);
}
});
it("writes \\atop, \\brace and \\brack as fractions without a bar", () => {
const noBar = new MathFraction({ numerator: [run("a")], denominator: [run("b")], type: "noBar" });
expect(read("{a \\atop b}")).toBe(written(noBar));
expect(read("{a \\brace b}")).toBe(written(new MathBrackets({ open: "{", close: "}", children: [noBar] })));
expect(read("{a \\brack b}")).toBe(written(new MathBrackets({ open: "[", close: "]", children: [noBar] })));
});
it("throws for two fractions written between numerator and denominator in one group", () => {
expect(() => latexToMath("{a \\over b \\over c}")).toThrow(
"\\over follows \\over in the same group. Put one of them in braces",
);
});
it("writes square roots and roots of any degree", () => {
expect(read("\\sqrt{x}")).toBe(written(new MathRadical({ children: [run("x")] })));
expect(read("\\sqrt[3]{x}")).toBe(written(new MathRadical({ children: [run("x")], degree: [run("3")] })));
expect(read("\\sqrt[]{x}")).toBe(written(new MathRadical({ children: [run("x")] })));
expect(read("\\sqrt2")).toBe(written(new MathRadical({ children: [run("2")] })));
});
it("throws for a root's degree with no closing bracket", () => {
expect(() => latexToMath("\\sqrt[3{x}")).toThrow("\\sqrt's option has no closing ]");
expect(() => latexToMath("\\sqrt[{3}")).toThrow("\\sqrt's option has no closing ]");
expect(() => latexToMath("\\sqrt[3}]{x}")).toThrow("a } has no { before it");
});
});
describe("large operators", () => {
it("writes a sum with its limits, over what comes after it up to a relation", () => {
expect(read("\\sum_{i=1}^n i^2 = S")).toBe(
written(
new MathLargeOperator({
operator: "sum",
subScript: [run("i=1")],
superScript: [run("n")],
children: [new MathSuperScript({ children: [run("i")], superScript: [run("2")] })],
}),
run("=S"),
),
);
});
it("ends what an operator applies to at a + or −, or punctuation, but not at a sign that comes first", () => {
expect(read("\\sum_i a_i + b")).toBe(
written(
new MathLargeOperator({
operator: "sum",
subScript: [run("i")],
children: [new MathSubScript({ children: [run("a")], subScript: [run("i")] })],
}),
run("+b"),
),
);
expect(read("\\prod -x, y")).toBe(written(new MathLargeOperator({ operator: "product", children: [run("−x")] }), run(",y")));
});
it("takes an integral's differential, and brackets whole, into what it applies to", () => {
expect(read("\\int_0^1 f(x+1)\\,dx")).toBe(
written(
new MathLargeOperator({
operator: "integral",
subScript: [run("0")],
superScript: [run("1")],
children: [run("f(x+1)\u2009dx")],
}),
),
);
});
it("ends at the bracket that closes the brackets it is in", () => {
expect(read("(\\sum a)^2")).toBe(
written(
run("("),
new MathLargeOperator({ operator: "sum", children: [run("a")] }),
new MathSuperScript({ children: [run(")")], superScript: [run("2")] }),
),
);
});
it("holds an operator that comes first, and ends at one that comes later", () => {
expect(read("\\sum_i \\sum_j a \\int b")).toBe(
written(
new MathLargeOperator({
operator: "sum",
subScript: [run("i")],
children: [new MathLargeOperator({ operator: "sum", subScript: [run("j")], children: [run("a")] })],
}),
new MathLargeOperator({ operator: "integral", children: [run("b")] }),
),
);
expect(read("\\int a \\int b")).toBe(
written(
new MathLargeOperator({ operator: "integral", children: [run("a")] }),
new MathLargeOperator({ operator: "integral", children: [run("b")] }),
),
);
});
it("takes built math and scripts on groups into what an operator applies to", () => {
expect(read("\\sum \\frac{1}{n} {ab}^2 = 1")).toBe(
written(
new MathLargeOperator({
operator: "sum",
children: [
new MathFraction({ numerator: [run("1")], denominator: [run("n")] }),
new MathSuperScript({ children: [run("ab")], superScript: [run("2")] }),
],
}),
run("=1"),
),
);
});
it("applies an operator to nothing when a relation follows it", () => {
expect(read("\\sum = 0")).toBe(written(new MathLargeOperator({ operator: "sum", children: [] }), run("=0")));
});
it("puts the limits where \\limits and \\nolimits say", () => {
expect(read("\\int\\limits_a^b x")).toBe(
written(
new MathLargeOperator({
operator: "integral",
limits: "aboveBelow",
subScript: [run("a")],
superScript: [run("b")],
children: [run("x")],
}),
),
);
expect(read("\\sum\\nolimits_k x")).toBe(
written(new MathLargeOperator({ operator: "sum", limits: "side", subScript: [run("k")], children: [run("x")] })),
);
});
it.each([
["prod", "product"],
["coprod", "coproduct"],
["bigcup", "union"],
["bigcap", "intersection"],
["bigsqcup", "squareUnion"],
["biguplus", "multisetUnion"],
["bigvee", "logicalOr"],
["bigwedge", "logicalAnd"],
["bigoplus", "directSum"],
["bigotimes", "tensorProduct"],
["bigodot", "circledDot"],
["iint", "doubleIntegral"],
["iiint", "tripleIntegral"],
["iiiint", "quadrupleIntegral"],
["oint", "contourIntegral"],
["oiint", "surfaceIntegral"],
["oiiint", "volumeIntegral"],
] as const)("writes \\%s as the %s operator", (command, operator) => {
expect(read(`\\${command} x`)).toBe(written(new MathLargeOperator({ operator, children: [run("x")] })));
});
});
describe("functions", () => {
it("writes a function's name upright, over what comes after it", () => {
expect(read("\\sin x + 1")).toBe(written(fn("sin", run("x")), run("+1")));
expect(read("\\cos(x+y) = 1")).toBe(written(fn("cos", run("(x+y)")), run("=1")));
expect(read("\\ln -x")).toBe(written(fn("ln", run("−x"))));
});
it("ends what a function applies to at another function, unless that comes first", () => {
expect(read("\\sin x \\cos y")).toBe(written(fn("sin", run("x")), fn("cos", run("y"))));
expect(read("\\log\\log n")).toBe(written(fn("log", fn("log", run("n")))));
});
it("writes a function applied to nothing with a zero-width space", () => {
expect(read("\\exp")).toBe(written(fn("exp", space())));
});
it("puts scripts on the name of a function whose limits don't go below it", () => {
expect(read("\\sin^2 x")).toBe(
written(
new MathFunction({
name: [new MathSuperScript({ children: [plain("sin")], superScript: [run("2")] })],
children: [run("x")],
}),
),
);
expect(read("\\log_2 n")).toBe(
written(
new MathFunction({
name: [new MathSubScript({ children: [plain("log")], subScript: [run("2")] })],
children: [run("n")],
}),
),
);
});
it("puts limits below lim and its like, and above for a superscript", () => {
expect(read("\\lim_{x\\to0} f")).toBe(
written(
new MathFunction({
name: [new MathLimitLower({ children: [plain("lim")], limit: [run("x→0")] })],
children: [run("f")],
}),
),
);
expect(read("\\max^{a} f")).toBe(
written(
new MathFunction({ name: [new MathLimitUpper({ children: [plain("max")], limit: [run("a")] })], children: [run("f")] }),
),
);
expect(read("\\sup_a^b f")).toBe(
written(
new MathFunction({
name: [
new MathLimitUpper({
children: [new MathLimitLower({ children: [plain("sup")], limit: [run("a")] })],
limit: [run("b")],
}),
],
children: [run("f")],
}),
),
);
expect(read("\\liminf x")).toBe(written(fn("lim\u2009inf", run("x"))));
});
it("puts lim's limits to the side for \\nolimits, and a function's below for \\limits", () => {
expect(read("\\lim\\nolimits_x f")).toBe(
written(
new MathFunction({
name: [new MathSubScript({ children: [plain("lim")], subScript: [run("x")] })],
children: [run("f")],
}),
),
);
expect(read("\\sin\\limits_x f")).toBe(
written(
new MathFunction({ name: [new MathLimitLower({ children: [plain("sin")], limit: [run("x")] })], children: [run("f")] }),
),
);
});
it("writes \\operatorname as a function, with its limits below for \\operatorname*", () => {
expect(read("\\operatorname{rank}(A)")).toBe(written(fn("rank", run("(A)"))));
expect(read("\\operatorname*{arg\\,max}_x f")).toBe(
written(
new MathFunction({
name: [new MathLimitLower({ children: [plain("arg\u2009max")], limit: [run("x")] })],
children: [run("f")],
}),
),
);
});
it("writes the modulo commands", () => {
expect(read("a \\bmod b")).toBe(written(run("a\u2004"), plain("mod"), run("\u2004b")));
expect(read("a \\mod b")).toBe(written(run("a\u2003"), plain("mod"), run("\u2004b")));
expect(read("a \\pmod{n}")).toBe(written(run("a\u2003("), plain("mod"), run("\u2004n)")));
expect(read("a \\pod n")).toBe(written(run("a\u2003(n)")));
});
});
describe("brackets", () => {
it("writes \\left and \\right as brackets that grow", () => {
expect(read("\\left( \\frac{a}{b} \\right)^2")).toBe(
written(
new MathSuperScript({
children: [new MathBrackets({ children: [new MathFraction({ numerator: [run("a")], denominator: [run("b")] })] })],
superScript: [run("2")],
}),
),
);
});
it("takes any delimiter, and a dot for none", () => {
expect(read("\\left\\{ x \\right.")).toBe(written(new MathBrackets({ open: "{", close: "", children: [run("x")] })));
expect(read("\\left. x \\right|")).toBe(written(new MathBrackets({ open: "", close: "|", children: [run("x")] })));
expect(read("\\left\\| v \\right\\Vert")).toBe(written(new MathBrackets({ open: "‖", close: "‖", children: [run("v")] })));
expect(read("\\left\\lvert x \\right\\rvert")).toBe(written(new MathBrackets({ open: "|", close: "|", children: [run("x")] })));
expect(read("\\left< x \\right>")).toBe(written(new MathBrackets({ open: "⟨", close: "⟩", children: [run("x")] })));
expect(read("\\left⌊ x \\right⌋")).toBe(written(new MathBrackets({ open: "⌊", close: "⌋", children: [run("x")] })));
expect(read("\\left[ x \\right\\rbrack")).toBe(written(new MathBrackets({ open: "[", close: "]", children: [run("x")] })));
});
it("writes \\middle as the separator between items", () => {
expect(read("\\left\\langle a \\middle| b \\middle| c \\right\\rangle")).toBe(
written(new MathBrackets({ open: "⟨", close: "⟩", separator: "|", items: [[run("a")], [run("b")], [run("c")]] })),
);
});
it("writes different \\middle delimiters as text, as Word has one separator for each pair of brackets", () => {
expect(read("\\left( a \\middle| b \\middle/ c \\right)")).toBe(
written(new MathBrackets({ children: [run("a"), run("|"), run("b"), run("/"), run("c")] })),
);
});
it("writes \\big and its like as the delimiter, which doesn't grow", () => {
expect(read("\\bigl( x \\bigr) \\Bigm| \\big. y")).toBe(written(run("(x)|y")));
expect(read("\\sin \\Big( x + y \\bigg) z")).toBe(written(fn("sin", run("(x+y)z"))));
});
it("throws for \\left with no \\right, and for \\right or \\middle with no \\left", () => {
expect(() => latexToMath("\\left( x")).toThrow("latexToMath: \\left has no \\right, at character 1");
expect(() => latexToMath("x \\right)")).toThrow("\\right has no \\left before it");
expect(() => latexToMath("x \\middle|")).toThrow("\\middle has no \\left before it");
expect(() => latexToMath("{\\left( x }")).toThrow("a } has no { before it");
});
it("throws for a delimiter it doesn't know, or none", () => {
expect(() => latexToMath("\\left x \\right)")).toThrow("\\left can't take \"x\", which isn't a delimiter");
expect(() => latexToMath("\\left\\alpha x \\right)")).toThrow("\\left can't take \\alpha, which isn't a delimiter");
expect(() => latexToMath("\\left")).toThrow("\\left needs a delimiter after it");
});
});
describe("accents, bars, braces, boxes and phantoms", () => {
it.each([
["hat", "hat"],
["widehat", "hat"],
["check", "check"],
["widecheck", "check"],
["tilde", "tilde"],
["widetilde", "tilde"],
["acute", "acute"],
["grave", "grave"],
["dot", "dot"],
["ddot", "doubleDot"],
["dddot", "tripleDot"],
["breve", "breve"],
["bar", "bar"],
["mathring", "ring"],
["vec", "rightArrow"],
["overrightarrow", "rightArrow"],
["overleftarrow", "leftArrow"],
["overleftrightarrow", "leftRightArrow"],
["overrightharpoon", "rightHarpoon"],
["overleftharpoon", "leftHarpoon"],
] as const)("writes \\%s as the %s accent", (command, accent) => {
expect(read(`\\${command}{x}`)).toBe(written(new MathAccent({ accent, children: [run("x")] })));
});
it("writes \\overline and \\underline as bars", () => {
expect(read("\\overline{AB} \\underline x")).toBe(
written(new MathBar({ children: [run("AB")] }), new MathBar({ position: "below", children: [run("x")] })),
);
});
it("writes braces, with the script on their other side as their label", () => {
expect(read("\\overbrace{a+b}^{n}")).toBe(written(new MathBrace({ children: [run("a+b")], label: [run("n")] })));
expect(read("\\underbrace{a+b}_n")).toBe(
written(new MathBrace({ position: "below", children: [run("a+b")], label: [run("n")] })),
);
expect(read("\\overbracket{a} \\underparen{b}")).toBe(
written(
new MathBrace({ brace: "square", children: [run("a")] }),
new MathBrace({ brace: "round", position: "below", children: [run("b")] }),
),
);
});
it("writes a script on the brace's own side as a script", () => {
expect(read("\\underbrace{a}^2")).toBe(
written(
new MathSuperScript({
children: [new MathBrace({ position: "below", children: [run("a")] })],
superScript: [run("2")],
}),
),
);
});
it("writes \\overset, \\underset and \\stackrel as limits", () => {
expect(read("\\overset{!}{=}")).toBe(written(new MathLimitUpper({ children: [run("=")], limit: [run("!")] })));
expect(read("\\stackrel{def}{=}")).toBe(written(new MathLimitUpper({ children: [run("=")], limit: [run("def")] })));
expect(read("\\underset{x}{ab}")).toBe(written(new MathLimitLower({ children: [run("ab")], limit: [run("x")] })));
});
it("ends what an operator applies to at a relation written with \\overset or \\stackrel", () => {
const sum = new MathLargeOperator({ operator: "sum", children: [run("a")] });
expect(read("\\sum a \\stackrel{?}{x} b")).toBe(
written(sum, new MathLimitUpper({ children: [run("x")], limit: [run("?")] }), run("b")),
);
expect(read("\\sum a \\overset{!}{=} b")).toBe(
written(sum, new MathLimitUpper({ children: [run("=")], limit: [run("!")] }), run("b")),
);
});
it("writes arrows with text above and below them", () => {
const arrow = new MathLimitUpper({ children: [run("→")], limit: [run("f")] });
expect(read("\\xrightarrow{f}")).toBe(written(arrow));
expect(read("\\xrightarrow[g]{f}")).toBe(written(new MathLimitLower({ children: [arrow], limit: [run("g")] })));
expect(read("\\xleftarrow{}")).toBe(written(new MathLimitUpper({ children: [run("←")], limit: [space()] })));
});
it("writes boxes and cancelled terms", () => {
expect(read("\\boxed{x}")).toBe(written(new MathBox({ children: [run("x")] })));
expect(read("\\fbox{if}")).toBe(written(new MathBox({ children: [words("if")] })));
expect(read("\\cancel{x}\\bcancel{y}\\xcancel{z}")).toBe(
written(
new MathBox({ borders: [], strikes: ["diagonalUp"], children: [run("x")] }),
new MathBox({ borders: [], strikes: ["diagonalDown"], children: [run("y")] }),
new MathBox({ borders: [], strikes: ["diagonalUp", "diagonalDown"], children: [run("z")] }),
),
);
});
it("writes phantoms", () => {
expect(read("\\phantom{x}")).toBe(written(new MathPhantom({ children: [run("x")] })));
expect(read("\\hphantom{x}")).toBe(written(new MathPhantom({ height: false, depth: false, children: [run("x")] })));
expect(read("\\vphantom{x}")).toBe(written(new MathPhantom({ width: false, children: [run("x")] })));
expect(read("\\smash{x}")).toBe(written(new MathPhantom({ visible: true, height: false, depth: false, children: [run("x")] })));
expect(read("\\smash[t]{x}")).toBe(
written(new MathPhantom({ visible: true, height: false, depth: true, children: [run("x")] })),
);
expect(read("\\smash[b]{x}")).toBe(
written(new MathPhantom({ visible: true, height: true, depth: false, children: [run("x")] })),
);
expect(read("\\mathstrut")).toBe(written(new MathPhantom({ width: false, children: [run("(")] })));
});
});
describe("fonts and text", () => {
it.each([
["mathrm", { style: "plain" }],
["mathup", { style: "plain" }],
["mathit", { style: "italic" }],
["mathbf", { style: "bold" }],
["bold", { style: "bold" }],
["boldsymbol", { style: "boldItalic" }],
["bm", { style: "boldItalic" }],
["pmb", { style: "boldItalic" }],
["mathbb", { script: "doubleStruck", style: "plain" }],
["Bbb", { script: "doubleStruck", style: "plain" }],
["mathcal", { script: "script", style: "plain" }],
["mathscr", { script: "script", style: "plain" }],
["mathfrak", { script: "fraktur", style: "plain" }],
["mathsf", { script: "sansSerif", style: "plain" }],
["mathtt", { script: "monospace", style: "plain" }],
] as const)("writes \\%s as a run in its font", (command, font) => {
expect(read(`\\${command}{R}`)).toBe(written(run("R", font)));
});
it("combines fonts, the inner one taking the place of the outer where they differ", () => {
expect(read("\\mathbf{\\mathbb{R}}")).toBe(written(run("R", { script: "doubleStruck", style: "bold" })));
expect(read("\\boldsymbol{\\mathcal{A}}")).toBe(written(run("A", { script: "script", style: "bold" })));
expect(read("\\mathcal{\\mathbf{A}}")).toBe(written(run("A", { script: "script", style: "bold" })));
expect(read("\\mathbb{\\mathrm{R}} \\mathbf{\\mathnormal{x}}")).toBe(written(plain("R"), run("x")));
});
it("changes the font for the rest of a group with \\bf and its like", () => {
expect(read("{a \\bf b} c")).toBe(written(run("a"), run("b", { style: "bold" }), run("c")));
expect(read("\\rm a \\it b \\sf c \\tt d \\cal e")).toBe(
written(
plain("a"),
run("b", { style: "italic" }),
run("c", { script: "sansSerif", style: "plain" }),
run("d", { script: "monospace", style: "plain" }),
run("e", { script: "script", style: "plain" }),
),
);
});
it("writes \\text and its like as normal text, keeping its spaces", () => {
expect(read("x \\text{ if } y")).toBe(written(run("x"), words(" if "), run("y")));
for (const command of [
"textrm",
"textnormal",
"textup",
"textmd",
"textbf",
"textit",
"textsl",
"textsf",
"texttt",
"emph",
"mbox",
"hbox",
]) {
expect(read(`\\${command}{a b}`), command).toBe(written(words("a b")));
}
});
it("writes text's spaces as one, and its escaped characters and dashes", () => {
expect(read("\\text{a \n b \\& c \\% \\$ \\# \\_ \\{ \\} \\textbackslash \\ldots}")).toBe(
written(words("a b & c % $ # _ { } \\…")),
);
expect(read("\\text{1--2---3 ``q'' `s' a~b}")).toBe(written(words("1–2—3 “q” ‘s’ a\u00A0b")));
expect(read("\\text{a\\quad b\\,c\\ d}")).toBe(written(words("a\u2003b\u2009c d")));
expect(read("\\text{\\dots\\textellipsis}")).toBe(written(words("……")));
});
it("reads text in text commands, and braces in text", () => {
expect(read("\\text{a \\textbf{b} {c}}")).toBe(written(words("a b c")));
});
it("reads math between dollar signs in text", () => {
expect(read("\\text{if $x^2 > 0$ then}")).toBe(
written(words("if "), new MathSuperScript({ children: [run("x")], superScript: [run("2")] }), run(">0"), words(" then")),
);
});
it("reads text of one character with no braces", () => {
expect(read("\\text a")).toBe(written(words("a")));
});
it("throws for text it can't read", () => {
expect(() => latexToMath("\\text{\\alpha}")).toThrow("unknown command \\alpha in text");
expect(() => latexToMath("\\text{a")).toThrow("\\text's argument has no closing }");
expect(() => latexToMath("\\text")).toThrow("\\text needs an argument");
expect(() => latexToMath("\\text\\alpha")).toThrow("\\text needs an argument");
expect(() => latexToMath("\\text{$x}")).toThrow("a } has no { before it");
expect(() => latexToMath("\\text{$x")).toThrow("math in text has no closing $");
});
it("leaves out colours, which Word's math has none of", () => {
expect(read("\\color{red} x \\textcolor{blue}{y}")).toBe(written(run("xy")));
});
it("writes \\mathop and its like as their argument", () => {
expect(read("\\mathop{a}\\mathbin{b}\\mathrel{c}\\mathord{d}\\mathopen{e}\\mathclose{f}\\mathpunct{g}\\mathinner{h}")).toBe(
written(run("abcdefgh")),
);
});
it("leaves out sizes, labels, lines between rows and other commands Word has no use for", () => {
expect(
read(
"\\displaystyle a \\textstyle \\scriptstyle \\scriptscriptstyle b \\label{eq} \\nonumber \\notag \\allowbreak \\nobreak \\limits c\\/",
),
).toBe(written(run("abc")));
});
it("writes \\hspace as a wide space", () => {
expect(read("a\\hspace{1em}b\\hspace*{2cm}c")).toBe(written(run("a\u2003b\u2003c")));
});
});
describe("environments", () => {
const cells = (...rows: readonly (readonly string[])[]): readonly (readonly (readonly MathComponent[])[])[] =>
rows.map((row) => row.map((text) => [run(text)]));
it.each([
["matrix", "none"],
["smallmatrix", "none"],
["pmatrix", "round"],
["bmatrix", "square"],
["Bmatrix", "curly"],
["vmatrix", "verticalBars"],
["Vmatrix", "doubleVerticalBars"],
] as const)("writes %s as a matrix in %s brackets", (environment, brackets) => {
expect(read(`\\begin{${environment}} 1 & 2 \\\\ 3 & 4 \\end{${environment}}`)).toBe(
written(new MathMatrix({ brackets, rows: cells(["1", "2"], ["3", "4"]) })),
);
});
it("gives short rows empty cells, and starts no row at a \\\\ at the end", () => {
expect(read("\\begin{matrix} a & b \\\\ c \\\\ \\end{matrix}")).toBe(
written(new MathMatrix({ rows: cells(["a", "b"], ["c"]) })),
);
});
it("skips a \\\\'s space, and lines between rows", () => {
expect(read("\\begin{matrix} a \\\\[2pt] \\hline b \\end{matrix}")).toBe(
written(new MathMatrix({ rows: cells(["a"], ["b"]) })),
);
});
it("lines up the columns of mathtools' starred matrices", () => {
expect(read("\\begin{pmatrix*}[r] 1 & 20 \\end{pmatrix*}")).toBe(
written(new MathMatrix({ brackets: "round", columnAlignment: "right", rows: cells(["1", "20"]) })),
);
expect(read("\\begin{bmatrix*} 1 \\end{bmatrix*}")).toBe(written(new MathMatrix({ brackets: "square", rows: cells(["1"]) })));
expect(() => latexToMath("\\begin{pmatrix*}[x] 1 \\end{pmatrix*}")).toThrow('\\begin{pmatrix*} can\'t line its columns up "x"');
});
it("writes an array as a matrix with its columns lined up, leaving out lines and spacing", () => {
expect(read("\\left( \\begin{array}{l|c@{\\,}rp{2cm}} a & b & c & d \\\\ e \\end{array} \\right)")).toBe(
written(
new MathBrackets({
children: [
new MathMatrix({
columnAlignment: ["left", "center", "right", "left"],
rows: cells(["a", "b", "c", "d"], ["e"]),
}),
],
}),
),
);
expect(read("\\begin{array}[t]{c} a & b \\end{array}")).toBe(
written(new MathMatrix({ columnAlignment: ["center", "center"], rows: cells(["a", "b"]) })),
);
expect(read("\\begin{subarray}{l} a \\\\ b \\end{subarray}")).toBe(
written(new MathMatrix({ columnAlignment: ["left"], rows: cells(["a"], ["b"]) })),
);
});
it("writes \\substack as one centred column", () => {
expect(read("\\sum_{\\substack{i<n \\\\ j<m}} a")).toBe(
written(
new MathLargeOperator({
operator: "sum",
subScript: [new MathMatrix({ rows: cells(["i<n"], ["j<m"]) })],
children: [run("a")],
}),
),
);
expect(() => latexToMath("\\substack x")).toThrow("\\substack needs an argument in braces");
expect(() => latexToMath("\\substack{a")).toThrow("\\substack's argument has no closing }");
});
it("writes cases, with or without conditions", () => {
for (const environment of ["cases", "dcases", "cases*"]) {
expect(read(`\\begin{${environment}} x & \\text{if } x \\ge 0 \\\\ 0 \\end{${environment}}`), environment).toBe(
written(
new MathCases({ cases: [{ value: [run("x")], condition: [words("if "), run("x≥0")] }, { value: [run("0")] }] }),
),
);
}
});
it("throws for a case of more than two parts", () => {
expect(() => latexToMath("\\begin{cases} a & b & c \\end{cases}")).toThrow(
"case 1 of \\begin{cases} has 3 parts, but a case has at most two: its value & its condition",
);
});
it("writes rcases with the brace on the right", () => {
expect(read("\\begin{rcases} a \\\\ b \\end{rcases}")).toBe(
written(
new MathBrackets({
open: "",
close: "}",
children: [new MathMatrix({ columnAlignment: "left", rows: cells(["a"], ["b"]) })],
}),
),
);
});
it("writes aligned equations, each row lined up at its &s, with the number \\tag gives it", () => {
expect(read("\\begin{align} y &= mx + b \\tag{1} \\\\ y' &= m \\tag*{(*)} \\\\ z &= 0 \\end{align}")).toBe(
written(
new MathEquationArray({
rows: [
{ parts: [[run("y")], [run("=mx+b")]], equationNumber: "(1)" },
{
parts: [[new MathSuperScript({ children: [run("y")], superScript: [run("′")] })], [run("=m")]],
equationNumber: "(*)",
},
{ parts: [[run("z")], [run("=0")]] },
],
}),
),
);
});
it("reads every environment of aligned equations", () => {
const array = written(new MathEquationArray({ rows: [{ parts: [[run("a")], [run("=b")]] }, { parts: [[], [run("=c")]] }] }));
for (const environment of ["aligned", "align*", "flalign", "eqnarray", "split", "gather", "gathered", "multline"]) {
expect(read(`\\begin{${environment}} a &= b \\\\ &= c \\end{${environment}}`), environment).toBe(array);
}
expect(read("\\begin{alignat}{2} a &= b \\\\ &= c \\end{alignat}")).toBe(array);
expect(read("\\begin{alignedat}{2} a &= b \\\\ &= c \\end{alignedat}")).toBe(array);
});
it("writes an equation as its math, or as a numbered row when it has a \\tag", () => {
expect(read("\\begin{equation} E = mc \\end{equation}")).toBe(written(run("E=mc")));
expect(read("\\begin{equation*} x \\end{equation*}")).toBe(written(run("x")));
expect(read("\\begin{equation} E = mc \\tag{2} \\label{energy} \\end{equation}")).toBe(
written(new MathEquationArray({ rows: [{ parts: [[run("E=mc")]], equationNumber: "(2)" }] })),
);
expect(read("\\begin{displaymath} a \\\\ b \\end{displaymath}")).toBe(
written(new MathEquationArray({ rows: [{ parts: [[run("a")]] }, { parts: [[run("b")]] }] })),
);
});
it("leaves out a \\tag inside braces, which has no row to number", () => {
expect(read("{a \\tag{1}}")).toBe(written(run("a")));
});
it("leaves dollar signs out of a \\tag", () => {
expect(read("a \\tag{$\\ast$}")).toBe(
written(new MathEquationArray({ rows: [{ parts: [[run("a")]], equationNumber: "(\\ast)" }] })),
);
});
it("throws for an environment it doesn't know, or one that doesn't end", () => {
expect(() => latexToMath("\\begin{tabular} a \\end{tabular}")).toThrow("unknown environment tabular");
expect(() => latexToMath("\\begin{matrix} a")).toThrow("latexToMath: \\begin{matrix} has no \\end{matrix}, at character 1");
expect(() => latexToMath("\\begin{matrix} a \\end{pmatrix}")).toThrow("\\begin{matrix} ends with \\end{pmatrix}");
expect(() => latexToMath("\\begin{matrix} a }")).toThrow("a } has no { before it");
expect(() => latexToMath("\\begin matrix")).toThrow("\\begin needs an argument in braces");
expect(() => latexToMath("\\begin{matrix")).toThrow("\\begin's argument has no closing }");
expect(() => latexToMath("a \\end{matrix}")).toThrow("\\end has no \\begin before it");
expect(() => latexToMath("\\smash[t")).toThrow("a [ has no closing ]");
});
});
describe("the whole equation", () => {
it("leaves out the delimiters math comes in", () => {
const math = written(run("x+1"));
for (const latex of ["$x+1$", "$$x+1$$", "\\(x+1\\)", "\\[x+1\\]", " $ x+1 $\n", "x+1"]) {
expect(read(latex), latex).toBe(math);
}
});
it("writes rows and parts outside an environment as aligned equations, as MathJax does", () => {
expect(read("a &= b \\\\ &= c")).toBe(
written(new MathEquationArray({ rows: [{ parts: [[run("a")], [run("=b")]] }, { parts: [[], [run("=c")]] }] })),
);
expect(read("E = mc^2 \\tag{3}")).toBe(
written(
new MathEquationArray({
rows: [
{
parts: [[run("E=m"), new MathSuperScript({ children: [run("c")], superScript: [run("2")] })]],
equationNumber: "(3)",
},
],
}),
),
);
});
it("writes nothing for no math", () => {
expect(latexToMath("")).toEqual([]);
expect(latexToMath("$$")).toEqual([]);
});
});
describe("errors", () => {
it("throws for the names of JavaScript's own object properties, which aren't commands", () => {
for (const name of ["constructor", "toString", "hasOwnProperty", "valueOf"]) {
expect(() => latexToMath(`\\${name}`), name).toThrow(`unknown command \\${name}`);
}
expect(() => latexToMath("\\begin{pmatrix*}[constructor] 1 \\end{pmatrix*}")).toThrow("can't line its columns up");
expect(() => latexToMath("\\begin{constructor} 1 \\end{constructor}")).toThrow("unknown environment constructor");
});
it("throws for a command it doesn't know, saying where it is", () => {
expect(() => latexToMath("\\frac{a}{\\foo}")).toThrow(
'latexToMath: unknown command \\foo, at character 10 of "\\frac{a}{\\foo}"',
);
});
it("shows the LaTeX around where it went wrong, when there is a lot of it", () => {
const latex = `${"a+".repeat(30)}\\foo${"+b".repeat(30)}`;
expect(() => latexToMath(latex)).toThrow(
`unknown command \\foo, at character 61 of "…${"a+".repeat(15)}\\foo${"+b".repeat(13)}…"`,
);
});
it("throws for braces that don't match", () => {
expect(() => latexToMath("{a")).toThrow("latexToMath: a { has no closing }, at character 1");
expect(() => latexToMath("a}")).toThrow("a } has no { before it");
expect(() => latexToMath("\\frac{a")).toThrow("\\frac's argument has no closing }");
});
it("throws for a missing argument", () => {
expect(() => latexToMath("\\frac{a}")).toThrow("\\frac needs an argument");
expect(() => latexToMath("\\sqrt")).toThrow("\\sqrt needs an argument");
expect(() => latexToMath("\\hat}")).toThrow("\\hat needs an argument");
});
it("throws for & and \\\\ where there are no rows or cells", () => {
expect(() => latexToMath("{a & b}")).toThrow(
"an & can only go between the rows and cells of a matrix or of aligned equations, not inside braces, brackets or \\left and \\right",
);
expect(() => latexToMath("\\left( a \\\\ b \\right)")).toThrow("a \\\\ can only go between the rows and cells");
expect(() => latexToMath("\\frac{a \\\\ b}{c}")).toThrow("a \\\\ can only go between the rows and cells");
});
it("throws for a dollar sign inside math, and a backslash at the end", () => {
expect(() => latexToMath("$a$ and $b$")).toThrow("a $ can only end math that is in \\text");
expect(() => latexToMath("a\\")).toThrow("a backslash ends the LaTeX, with no command after it");
});
it("throws for \\not before something that can't be struck through", () => {
expect(() => latexToMath("\\not")).toThrow("\\not needs a symbol after it");
expect(() => latexToMath("\\not{=}")).toThrow("\\not needs a symbol after it");
expect(() => latexToMath("\\not\\frac")).toThrow("\\not needs a symbol after it");
});
});
});
+55
View File
@@ -0,0 +1,55 @@
/**
* LaTeX math, as docx's math: `latexToMath`.
*
* @module
*/
// cspell:ignore mathbb mathrm
import type { MathComponent } from "docx";
import { atomsToMath } from "./latex/latex-atoms";
import { equationArrayOf, parseLatex } from "./latex/latex-parser";
// The delimiters math can come in, which are left out. $$ comes before $, so it isn't read as $ and $
const DELIMITERS: readonly (readonly [string, string])[] = [
["$$", "$$"],
["\\[", "\\]"],
["\\(", "\\)"],
["$", "$"],
];
/**
* Turns LaTeX math into docx's math, to go in a `Math`, as Word's own equations, which it shows and edits as it does
* those typed into it.
*
* It reads the math that LaTeX, MathJax and KaTeX write: fractions, scripts, roots, sums, integrals and other large
* operators, functions such as sin and lim, brackets that grow with `\left` and `\right`, accents, braces, boxes,
* fonts such as `\mathbb` and `\mathrm`, `\text`, Greek letters and symbols, and the environments for matrices,
* cases and aligned equations, with `\tag` for their numbers. The math can be given in `$…$`, `$$…$$`, `\(…\)` or
* `\[…\]`, which are left out.
*
* Colours, sizes and spacing that Word works out for itself are left out.
*
* @param latex - The LaTeX, such as `"\\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}"`
* @returns The math, to be the children of a `Math`, or to go among other math components
* @throws If the LaTeX has a command or an environment it doesn't know, or isn't well formed, such as a `{` with no
* `}`. The error says where
*
* @example
* ```typescript
* new Math({ children: latexToMath("x = \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}") });
* ```
*/
export const latexToMath = (latex: string): readonly MathComponent[] => {
const start = latex.length - latex.trimStart().length;
const end = latex.trimEnd().length;
const [open, close] = DELIMITERS.find(
([opening, closing]) =>
end - start >= opening.length + closing.length && latex.startsWith(opening, start) && latex.endsWith(closing, end),
) ?? ["", ""];
const rows = parseLatex(latex, start + open.length, end - close.length);
return rows.length === 1 && rows[0].cells.length === 1 && rows[0].tag === undefined
? atomsToMath(rows[0].cells[0])
: [equationArrayOf(rows)];
};
+212
View File
@@ -0,0 +1,212 @@
/**
* What the LaTeX parser reads an equation into, and how that becomes docx's math: runs of text that share a font are
* joined, scripts go on their bases, and large operators and functions take the math after them as their argument.
*
* @module
*/
import {
type MathComponent,
MathFunction,
MathLimitLower,
MathLimitUpper,
type MathLimitsPosition,
MathRun,
type MathRunOptions,
MathSubScript,
MathSubSuperScript,
MathSuperScript,
} from "docx";
import { MathLargeOperator, type MathLargeOperatorName } from "../math-large-operator";
import type { SymbolRole } from "./latex-symbols";
/** How text is written: its style and alphabet, or as normal text, and whether it is taken literally */
export type Font = Omit<MathRunOptions, "text">;
/** A piece of an equation, as the parser reads it */
export type Atom =
/** A symbol or a run of text, which is joined to the text around it in the same font */
| { readonly kind: "text"; readonly text: string; readonly font: Font; readonly role: SymbolRole }
/** A group in braces, which scripts take as their base, and which is otherwise part of the math around it */
| { readonly kind: "group"; readonly atoms: readonly Atom[] }
/** Math already built, such as a fraction or a matrix */
| { readonly kind: "built"; readonly component: MathComponent; readonly role?: SymbolRole }
/** A base with a subscript, a superscript or both */
| { readonly kind: "scripts"; readonly base: readonly Atom[]; readonly sub?: readonly Atom[]; readonly sup?: readonly Atom[] }
/** A large operator, such as ∑, whose argument is the math after it */
| {
readonly kind: "operator";
readonly operator: MathLargeOperatorName;
readonly limits?: MathLimitsPosition;
readonly sub?: readonly Atom[];
readonly sup?: readonly Atom[];
}
/** A function, such as sin or lim, whose argument is the math after it */
| {
readonly kind: "function";
readonly name: readonly Atom[];
/** Whether its limits go below it, as lim's do, rather than to its right */
readonly limitsBelow: boolean;
readonly sub?: readonly Atom[];
readonly sup?: readonly Atom[];
}
/** An equation number, from `\tag`, which the row it is in takes */
| { readonly kind: "tag"; readonly text: string };
/** The atoms with a subscript or superscript of their own, rather than a base in a script */
export type AtomWithLimits = Extract<Atom, { readonly kind: "operator" | "function" }>;
const ZERO_WIDTH_SPACE = "\u200B";
/**
* The part an atom plays, which says where an operator's argument ends. A script's is its base's, so the bracket in
* `)^2` still closes.
*/
const roleOf = (atom: Atom): SymbolRole => {
switch (atom.kind) {
case "text":
return atom.role;
case "built":
return atom.role ?? "ordinary";
case "scripts":
return atom.base.length === 1 ? roleOf(atom.base[0]) : "ordinary";
default:
return "ordinary";
}
};
/**
* Where the argument of the operator or function before `start` ends. LaTeX doesn't say, so it goes as far as TeX's
* spacing suggests: to a relation, a + or −, or punctuation, or to another operator or function, outside brackets.
* So ∑ᵢ aᵢ + b takes aᵢ, ∫ f(x) dx takes f(x) dx, and sin(x + y) takes (x + y). An operator that comes first is part
* of the argument, as in ∑ᵢ ∑ⱼ aᵢⱼ, and so is a sign, as in sin −x.
*/
const argumentEnd = (atoms: readonly Atom[], start: number): number => {
let depth = 0;
for (let index = start; index < atoms.length; index++) {
const atom = atoms[index];
const role = roleOf(atom);
if (depth === 0) {
if (role === "relation" || role === "punctuation" || role === "close") {
return index;
}
if (index > start && (role === "additive" || atom.kind === "operator" || atom.kind === "function")) {
return index;
}
}
if (role === "open") {
depth++;
} else if (role === "close") {
depth--;
}
}
return atoms.length;
};
/** An argument's math, with a zero-width space when it is empty, which LibreOffice needs to read the equation */
export const orSpace = (children: readonly MathComponent[]): readonly MathComponent[] =>
children.length === 0 ? [new MathRun(ZERO_WIDTH_SPACE)] : children;
const isPlain = (font: Font): boolean => Object.values(font).every((value) => value === undefined || value === false);
const sameFont = (one: Font, other: Font): boolean =>
one.style === other.style &&
one.script === other.script &&
!!one.normalText === !!other.normalText &&
!!one.literal === !!other.literal;
const createRun = (text: string, font: Font): MathRun => new MathRun(isPlain(font) ? text : { text, ...font });
const withScripts = (base: readonly MathComponent[], sub: readonly Atom[] | undefined, sup: readonly Atom[] | undefined): MathComponent => {
const children = orSpace(base);
if (sub !== undefined && sup !== undefined) {
return new MathSubSuperScript({ children, subScript: orSpace(atomsToMath(sub)), superScript: orSpace(atomsToMath(sup)) });
}
if (sub !== undefined) {
return new MathSubScript({ children, subScript: orSpace(atomsToMath(sub)) });
}
// A script atom has a subscript, a superscript or both
return new MathSuperScript({ children, superScript: orSpace(atomsToMath(sup!)) });
};
const createOperator = (atom: AtomWithLimits, argument: readonly MathComponent[]): MathComponent => {
if (atom.kind === "operator") {
return new MathLargeOperator({
operator: atom.operator,
limits: atom.limits,
subScript: atom.sub && orSpace(atomsToMath(atom.sub)),
superScript: atom.sup && orSpace(atomsToMath(atom.sup)),
children: argument,
});
}
const name = atomsToMath(atom.name);
const hasScripts = atom.sub !== undefined || atom.sup !== undefined;
const below = atom.sub === undefined ? name : [new MathLimitLower({ children: name, limit: orSpace(atomsToMath(atom.sub)) })];
const limited = atom.sup === undefined ? below : [new MathLimitUpper({ children: below, limit: orSpace(atomsToMath(atom.sup)) })];
const scripted = hasScripts ? [withScripts(name, atom.sub, atom.sup)] : name;
return new MathFunction({ name: atom.limitsBelow ? limited : scripted, children: orSpace(argument) });
};
/** A piece of written math: text, which is joined to the text next to it in the same font, or a component */
type Piece =
| { readonly kind: "text"; readonly text: string; readonly font: Font }
| { readonly kind: "component"; readonly component: MathComponent };
/**
* Turns atoms into pieces of math. A group's pieces are among those around it, so its text can join theirs, as in
* `a{b}c`.
*/
const atomsToPieces = (atoms: readonly Atom[]): readonly Piece[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const pieces: Piece[] = [];
for (let index = 0; index < atoms.length; index++) {
const atom = atoms[index];
switch (atom.kind) {
case "text":
// eslint-disable-next-line functional/immutable-data
pieces.push({ kind: "text", text: atom.text, font: atom.font });
break;
case "group":
// eslint-disable-next-line functional/immutable-data
pieces.push(...atomsToPieces(atom.atoms));
break;
case "built":
// eslint-disable-next-line functional/immutable-data
pieces.push({ kind: "component", component: atom.component });
break;
case "scripts":
// eslint-disable-next-line functional/immutable-data
pieces.push({ kind: "component", component: withScripts(atomsToMath(atom.base), atom.sub, atom.sup) });
break;
case "operator":
case "function": {
const end = argumentEnd(atoms, index + 1);
// eslint-disable-next-line functional/immutable-data
pieces.push({ kind: "component", component: createOperator(atom, atomsToMath(atoms.slice(index + 1, end))) });
index = end - 1;
break;
}
default:
// A tag is taken by its row, and written as the row's equation number
break;
}
}
return pieces;
};
/**
* Turns atoms into docx's math, with text next to text in the same font joined in one run.
*/
export const atomsToMath = (atoms: readonly Atom[]): readonly MathComponent[] =>
atomsToPieces(atoms)
.reduce<readonly Piece[]>((joined, piece) => {
const last = joined[joined.length - 1];
return piece.kind === "text" && last?.kind === "text" && sameFont(last.font, piece.font)
? [...joined.slice(0, -1), { ...last, text: last.text + piece.text }]
: [...joined, piece];
}, [])
.map((piece) => (piece.kind === "text" ? createRun(piece.text, piece.font) : piece.component));
File diff suppressed because it is too large Load Diff
+680
View File
@@ -0,0 +1,680 @@
/**
* LaTeX's math symbols, as the characters Word writes, and what part each plays in an equation.
*
* @module
*/
// The tables are LaTeX's command names, which aren't words
/* cspell:disable */
import type { MathAccentName } from "../math-accent";
import type { MathBraceShape } from "../math-brace";
import type { MathLargeOperatorName } from "../math-large-operator";
/**
* The part a symbol plays, as TeX's classes of atoms, which says where an operator's or function's argument ends:
*
* - `"ordinary"`: letters, digits and most symbols;
* - `"binary"`: operators between two things, such as × and ∪;
* - `"additive"`: the binary operators + − ± ∓, which end an operator's argument, as in ∑aᵢ + b;
* - `"relation"`: =, <, ∈, arrows and the like, which end it too;
* - `"punctuation"`: , and ;, which end it too;
* - `"open"` and `"close"`: brackets, which an argument holds in pairs.
*/
export type SymbolRole = "ordinary" | "binary" | "additive" | "relation" | "punctuation" | "open" | "close";
/** A symbol: its character or characters, and its part */
export type LatexSymbol = {
readonly text: string;
readonly role: SymbolRole;
};
/**
* Whether a table has an entry of its own for a key. Unlike `in`, it isn't fooled by the names every object has, such as
* `\constructor`.
*/
export const hasEntry = (table: object, key: string): boolean => Object.prototype.hasOwnProperty.call(table, key);
const withRole = (role: SymbolRole, symbols: Readonly<Record<string, string>>): readonly (readonly [string, LatexSymbol])[] =>
Object.entries(symbols).map(([name, text]) => [name, { text, role }]);
/** Spaces, which some commands write */
export const QUAD = "\u2003";
export const THICK_SPACE = "\u2004";
const GREEK: Readonly<Record<string, string>> = {
alpha: "α",
beta: "β",
gamma: "γ",
delta: "δ",
epsilon: "ϵ",
varepsilon: "ε",
zeta: "ζ",
eta: "η",
theta: "θ",
vartheta: "ϑ",
iota: "ι",
kappa: "κ",
varkappa: "ϰ",
lambda: "λ",
mu: "μ",
nu: "ν",
xi: "ξ",
omicron: "ο",
pi: "π",
varpi: "ϖ",
rho: "ρ",
varrho: "ϱ",
sigma: "σ",
varsigma: "ς",
tau: "τ",
upsilon: "υ",
phi: "ϕ",
varphi: "φ",
chi: "χ",
psi: "ψ",
omega: "ω",
digamma: "ϝ",
};
/** Capital Greek letters, which LaTeX draws upright */
export const UPRIGHT_GREEK: Readonly<Record<string, string>> = {
Gamma: "Γ",
Delta: "Δ",
Theta: "Θ",
Lambda: "Λ",
Xi: "Ξ",
Pi: "Π",
Sigma: "Σ",
Upsilon: "Υ",
Phi: "Φ",
Psi: "Ψ",
Omega: "Ω",
};
/** Capital Greek letters in italic, as amsmath's `\varGamma` */
export const ITALIC_GREEK: Readonly<Record<string, string>> = Object.fromEntries(
Object.entries(UPRIGHT_GREEK).map(([name, text]) => [`var${name}`, text]),
);
const ORDINARY: Readonly<Record<string, string>> = {
...GREEK,
infty: "∞",
partial: "∂",
nabla: "∇",
forall: "∀",
exists: "∃",
nexists: "∄",
emptyset: "∅",
varnothing: "∅",
neg: "¬",
lnot: "¬",
angle: "∠",
measuredangle: "∡",
sphericalangle: "∢",
triangle: "△",
hbar: "ℏ",
hslash: "ℏ",
ell: "ℓ",
wp: "℘",
Re: "ℜ",
Im: "ℑ",
aleph: "ℵ",
beth: "ℶ",
gimel: "ℷ",
daleth: "ℸ",
imath: "ı",
jmath: "ȷ",
prime: "′",
backprime: "‵",
top: "⊤",
bot: "⊥",
ldots: "…",
dots: "…",
dotsc: "…",
dotso: "…",
cdots: "⋯",
dotsb: "⋯",
dotsm: "⋯",
dotsi: "⋯",
vdots: "⋮",
ddots: "⋱",
iddots: "⋰",
square: "□",
Box: "□",
blacksquare: "■",
Diamond: "◇",
lozenge: "◊",
blacklozenge: "⧫",
clubsuit: "♣",
diamondsuit: "♢",
heartsuit: "♡",
spadesuit: "♠",
flat: "♭",
natural: "♮",
sharp: "♯",
surd: "√",
mho: "℧",
complement: "∁",
dag: "†",
ddag: "‡",
S: "§",
P: "¶",
copyright: "©",
pounds: "£",
euro: "€",
yen: "¥",
degree: "°",
bigstar: "★",
checkmark: "✓",
maltese: "✠",
backslash: "\\",
Vert: "‖",
vert: "|",
};
const BINARY: Readonly<Record<string, string>> = {
times: "×",
div: "÷",
cdot: "⋅",
centerdot: "⋅",
ast: "∗",
star: "⋆",
circ: "∘",
bullet: "∙",
oplus: "⊕",
ominus: "⊖",
otimes: "⊗",
oslash: "⊘",
odot: "⊙",
circledast: "⊛",
circledcirc: "⊚",
boxplus: "⊞",
boxminus: "⊟",
boxtimes: "⊠",
boxdot: "⊡",
cup: "∪",
cap: "∩",
sqcup: "⊔",
sqcap: "⊓",
uplus: "⊎",
vee: "∨",
lor: "∨",
wedge: "∧",
land: "∧",
setminus: "∖",
smallsetminus: "∖",
wr: "≀",
amalg: "⨿",
diamond: "⋄",
triangleleft: "◁",
triangleright: "▷",
bigtriangleup: "△",
bigtriangledown: "▽",
lhd: "⊲",
rhd: "⊳",
unlhd: "⊴",
unrhd: "⊵",
ltimes: "⋉",
rtimes: "⋊",
dotplus: "∔",
Cup: "⋓",
Cap: "⋒",
intercal: "⊺",
barwedge: "⌅",
veebar: "⊻",
divideontimes: "⋇",
leftthreetimes: "⋋",
rightthreetimes: "⋌",
curlyvee: "⋎",
curlywedge: "⋏",
bigcirc: "◯",
dagger: "†",
ddagger: "‡",
};
const ADDITIVE: Readonly<Record<string, string>> = {
pm: "±",
mp: "∓",
};
const RELATION: Readonly<Record<string, string>> = {
le: "≤",
leq: "≤",
ge: "≥",
geq: "≥",
leqslant: "⩽",
geqslant: "⩾",
leqq: "≦",
geqq: "≧",
ne: "≠",
neq: "≠",
equiv: "≡",
approx: "≈",
approxeq: "≊",
sim: "∼",
simeq: "≃",
backsim: "∽",
cong: "≅",
propto: "∝",
varpropto: "∝",
in: "∈",
notin: "∉",
ni: "∋",
owns: "∋",
subset: "⊂",
subseteq: "⊆",
supset: "⊃",
supseteq: "⊇",
subsetneq: "⊊",
supsetneq: "⊋",
subseteqq: "⫅",
supseteqq: "⫆",
nsubseteq: "⊈",
nsupseteq: "⊉",
sqsubset: "⊏",
sqsupset: "⊐",
sqsubseteq: "⊑",
sqsupseteq: "⊒",
mid: "∣",
nmid: "∤",
shortmid: "∣",
parallel: "∥",
nparallel: "∦",
shortparallel: "∥",
perp: "⊥",
models: "⊨",
vdash: "⊢",
dashv: "⊣",
vDash: "⊨",
Vdash: "⊩",
ll: "≪",
gg: "≫",
lll: "⋘",
ggg: "⋙",
prec: "≺",
succ: "≻",
preceq: "⪯",
succeq: "⪰",
doteq: "≐",
asymp: "≍",
bowtie: "⋈",
Join: "⨝",
smile: "⌣",
frown: "⌢",
coloneqq: "≔",
coloneq: "≔",
eqqcolon: "≕",
triangleq: "≜",
lesssim: "≲",
gtrsim: "≳",
lessgtr: "≶",
gtrless: "≷",
nless: "≮",
ngtr: "≯",
nleq: "≰",
ngeq: "≱",
nsim: "≁",
ncong: "≇",
lneq: "⪇",
gneq: "⪈",
lneqq: "≨",
gneqq: "≩",
therefore: "∴",
because: "∵",
circeq: "≗",
bumpeq: "≏",
Bumpeq: "≎",
risingdotseq: "≓",
fallingdotseq: "≒",
vartriangleleft: "⊲",
vartriangleright: "⊳",
trianglelefteq: "⊴",
trianglerighteq: "⊵",
between: "≬",
pitchfork: "⋔",
colon: ":",
to: "→",
rightarrow: "→",
leftarrow: "←",
gets: "←",
leftrightarrow: "↔",
Rightarrow: "⇒",
Leftarrow: "⇐",
Leftrightarrow: "⇔",
implies: "⟹",
impliedby: "⟸",
iff: "⟺",
longrightarrow: "⟶",
longleftarrow: "⟵",
longleftrightarrow: "⟷",
Longrightarrow: "⟹",
Longleftarrow: "⟸",
Longleftrightarrow: "⟺",
mapsto: "↦",
longmapsto: "⟼",
hookrightarrow: "↪",
hookleftarrow: "↩",
uparrow: "↑",
downarrow: "↓",
updownarrow: "↕",
Uparrow: "⇑",
Downarrow: "⇓",
Updownarrow: "⇕",
nearrow: "↗",
searrow: "↘",
swarrow: "↙",
nwarrow: "↖",
rightharpoonup: "⇀",
rightharpoondown: "⇁",
leftharpoonup: "↼",
leftharpoondown: "↽",
rightleftharpoons: "⇌",
leftrightharpoons: "⇋",
upharpoonright: "↾",
upharpoonleft: "↿",
downharpoonright: "⇂",
downharpoonleft: "⇃",
twoheadrightarrow: "↠",
twoheadleftarrow: "↞",
rightarrowtail: "↣",
leftarrowtail: "↢",
leadsto: "⇝",
rightsquigarrow: "⇝",
leftrightsquigarrow: "↭",
curvearrowright: "↷",
curvearrowleft: "↶",
circlearrowright: "↻",
circlearrowleft: "↺",
rightrightarrows: "⇉",
leftleftarrows: "⇇",
rightleftarrows: "⇄",
leftrightarrows: "⇆",
Rrightarrow: "⇛",
Lleftarrow: "⇚",
nrightarrow: "↛",
nleftarrow: "↚",
nRightarrow: "⇏",
nLeftarrow: "⇍",
nleftrightarrow: "↮",
nLeftrightarrow: "⇎",
looparrowright: "↬",
looparrowleft: "↫",
multimap: "⊸",
};
/** Brackets, which `\left`, `\right`, `\middle` and `\big` take too */
const OPENING: Readonly<Record<string, string>> = {
langle: "⟨",
lceil: "⌈",
lfloor: "⌊",
lvert: "|",
lVert: "‖",
lbrace: "{",
lbrack: "[",
ulcorner: "⌜",
llcorner: "⌞",
lgroup: "⟮",
lmoustache: "⎰",
llbracket: "⟦",
};
const CLOSING: Readonly<Record<string, string>> = {
rangle: "⟩",
rceil: "⌉",
rfloor: "⌋",
rvert: "|",
rVert: "‖",
rbrace: "}",
rbrack: "]",
urcorner: "⌝",
lrcorner: "⌟",
rgroup: "⟯",
rmoustache: "⎱",
rrbracket: "⟧",
};
// Symbols written with a backslash and a character, such as \{ and \|. The character # is taken literally, as it has
// a meaning in equation arrays
const ESCAPED_ORDINARY: Readonly<Record<string, string>> = Object.fromEntries([
["%", "%"],
["$", "$"],
["_", "_"],
["|", "‖"],
]);
/** The symbols LaTeX writes with a command, by the command's name without its backslash */
export const SYMBOLS: ReadonlyMap<string, LatexSymbol> = new Map([
...withRole("ordinary", { ...ORDINARY, ...ESCAPED_ORDINARY }),
...withRole("binary", BINARY),
...withRole("additive", ADDITIVE),
...withRole("relation", RELATION),
...withRole("open", { ...OPENING, ...Object.fromEntries([["{", "{"]]) }),
...withRole("close", { ...CLOSING, ...Object.fromEntries([["}", "}"]]) }),
]);
/** Characters typed as they are, which Word writes as another character or which play a part */
export const CHARACTERS: ReadonlyMap<string, LatexSymbol> = new Map<string, LatexSymbol>([
["+", { text: "+", role: "additive" }],
// The minus sign, not the hyphen, as LaTeX draws it
["-", { text: "−", role: "additive" }],
["*", { text: "∗", role: "binary" }],
["=", { text: "=", role: "relation" }],
["<", { text: "<", role: "relation" }],
[">", { text: ">", role: "relation" }],
[":", { text: ":", role: "relation" }],
[",", { text: ",", role: "punctuation" }],
[";", { text: ";", role: "punctuation" }],
["(", { text: "(", role: "open" }],
["[", { text: "[", role: "open" }],
[")", { text: ")", role: "close" }],
["]", { text: "]", role: "close" }],
]);
// The part a character plays when it is typed as it is, such as ≤ in place of \le
const ROLES_OF_CHARACTERS: ReadonlyMap<string, SymbolRole> = new Map(
[...SYMBOLS.values(), ...CHARACTERS.values()]
.filter(({ text, role }) => role !== "ordinary" && text !== "|" && text !== "‖")
.map(({ text, role }) => [text, role]),
);
/** The part a character plays, whether it was typed as it is or written with a command */
export const roleOf = (character: string): SymbolRole => ROLES_OF_CHARACTERS.get(character) ?? "ordinary";
/** The delimiters typed as they are, which `\left`, `\right`, `\middle` and `\big` take. A dot is none */
export const DELIMITER_CHARACTERS: ReadonlyMap<string, string> = new Map([
["(", "("],
[")", ")"],
["[", "["],
["]", "]"],
["|", "|"],
["/", "/"],
["<", "⟨"],
[">", "⟩"],
[".", ""],
]);
/** The delimiters `\left`, `\right`, `\middle` and `\big` take, by their command's name */
export const DELIMITER_COMMANDS: ReadonlyMap<string, string> = new Map([
...Object.entries(OPENING),
...Object.entries(CLOSING),
["{", "{"],
["}", "}"],
["|", "‖"],
...Object.entries({
vert: "|",
Vert: "‖",
backslash: "\\",
uparrow: "↑",
downarrow: "↓",
updownarrow: "↕",
Uparrow: "⇑",
Downarrow: "⇓",
Updownarrow: "⇕",
}),
]);
/** Relations with a line through them, for `\not`: the character Unicode has for each */
export const NEGATIONS: ReadonlyMap<string, string> = new Map([
["=", "≠"],
["<", "≮"],
[">", "≯"],
["≤", "≰"],
["≥", "≱"],
["≡", "≢"],
["∼", "≁"],
["≃", "≄"],
["≈", "≉"],
["≅", "≇"],
["∈", "∉"],
["∋", "∌"],
["⊂", "⊄"],
["⊃", "⊅"],
["⊆", "⊈"],
["⊇", "⊉"],
["∣", "∤"],
["∥", "∦"],
["≺", "⊀"],
["≻", "⊁"],
["⊢", "⊬"],
["⊨", "⊭"],
["∃", "∄"],
["→", "↛"],
["←", "↚"],
["↔", "↮"],
["⇒", "⇏"],
["⇐", "⇍"],
["⇔", "⇎"],
]);
/** Spaces, by their command's name */
export const SPACES: ReadonlyMap<string, string> = new Map([
[",", "\u2009"],
["thinspace", "\u2009"],
[":", "\u2005"],
[">", "\u2005"],
["medspace", "\u2005"],
[";", "\u2004"],
["thickspace", "\u2004"],
[" ", "\u2004"],
["space", "\u2004"],
["enspace", "\u2002"],
["quad", "\u2003"],
["qquad", "\u2003\u2003"],
// Negative spaces, which Word has no way to write
["!", ""],
["negthinspace", ""],
["negmedspace", ""],
["negthickspace", ""],
]);
/** Functions, which LaTeX writes upright with a thin space after them */
export const FUNCTIONS: Readonly<Record<string, string>> = {
arccos: "arccos",
arcsin: "arcsin",
arctan: "arctan",
arg: "arg",
cos: "cos",
cosh: "cosh",
cot: "cot",
coth: "coth",
csc: "csc",
deg: "deg",
dim: "dim",
exp: "exp",
hom: "hom",
ker: "ker",
lg: "lg",
ln: "ln",
log: "log",
sec: "sec",
sin: "sin",
sinh: "sinh",
tan: "tan",
tanh: "tanh",
};
/** Functions whose limits go below them in a display, such as lim with x → 0 below it */
export const FUNCTIONS_WITH_LIMITS: Readonly<Record<string, string>> = {
det: "det",
gcd: "gcd",
inf: "inf",
lim: "lim",
liminf: "lim\u2009inf",
limsup: "lim\u2009sup",
max: "max",
min: "min",
Pr: "Pr",
sup: "sup",
};
/** Large operators, by their command's name */
export const LARGE_OPERATOR_COMMANDS: Readonly<Record<string, MathLargeOperatorName>> = {
sum: "sum",
prod: "product",
coprod: "coproduct",
bigcup: "union",
bigcap: "intersection",
bigsqcup: "squareUnion",
biguplus: "multisetUnion",
bigvee: "logicalOr",
bigwedge: "logicalAnd",
bigoplus: "directSum",
bigotimes: "tensorProduct",
bigodot: "circledDot",
int: "integral",
iint: "doubleIntegral",
iiint: "tripleIntegral",
iiiint: "quadrupleIntegral",
oint: "contourIntegral",
oiint: "surfaceIntegral",
oiiint: "volumeIntegral",
};
/** Accents, by their command's name */
export const ACCENT_COMMANDS: Readonly<Record<string, MathAccentName>> = {
hat: "hat",
widehat: "hat",
check: "check",
widecheck: "check",
tilde: "tilde",
widetilde: "tilde",
acute: "acute",
grave: "grave",
dot: "dot",
ddot: "doubleDot",
dddot: "tripleDot",
breve: "breve",
bar: "bar",
mathring: "ring",
vec: "rightArrow",
overrightarrow: "rightArrow",
overleftarrow: "leftArrow",
overleftrightarrow: "leftRightArrow",
overrightharpoon: "rightHarpoon",
overleftharpoon: "leftHarpoon",
};
/** Braces over and under math, by their command's name */
export const BRACE_COMMANDS: Readonly<Record<string, { readonly brace: MathBraceShape; readonly position: "above" | "below" }>> = {
overbrace: { brace: "curly", position: "above" },
underbrace: { brace: "curly", position: "below" },
overbracket: { brace: "square", position: "above" },
underbracket: { brace: "square", position: "below" },
overparen: { brace: "round", position: "above" },
underparen: { brace: "round", position: "below" },
};
/** Arrows that stretch to fit text above and below them, by their command's name */
export const EXTENSIBLE_ARROWS: Readonly<Record<string, string>> = {
xrightarrow: "→",
xleftarrow: "←",
xleftrightarrow: "↔",
xRightarrow: "⇒",
xLeftarrow: "⇐",
xLeftrightarrow: "⇔",
xmapsto: "↦",
xhookrightarrow: "↪",
xhookleftarrow: "↩",
xrightharpoonup: "⇀",
xrightleftharpoons: "⇌",
};
/* cspell:enable */
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import xml from "xml";
import { Formatter } from "@export/formatter";
import { Math, MathRun } from "docx";
import { MathAccent, type MathAccentName } from "./math-accent";
const toXml = (component: MathAccent): string => xml(new Formatter().format(component));
const x = "<m:e><m:r><m:t>x</m:t></m:r></m:e>";
describe("MathAccent", () => {
it("puts a hat over its children by default", () => {
expect(toXml(new MathAccent({ children: [new MathRun("x")] }))).toBe(
`<m:acc><m:accPr><m:chr m:val="\u0302"/></m:accPr>${x}</m:acc>`,
);
});
it.each<readonly [MathAccentName, string]>([
["hat", "\u0302"],
["check", "\u030C"],
["tilde", "\u0303"],
["acute", "\u0301"],
["grave", "\u0300"],
["dot", "\u0307"],
["doubleDot", "\u0308"],
["tripleDot", "\u20DB"],
["breve", "\u0306"],
["bar", "\u0305"],
["ring", "\u030A"],
["rightArrow", "\u20D7"],
["leftArrow", "\u20D6"],
["leftRightArrow", "\u20E1"],
["rightHarpoon", "\u20D1"],
["leftHarpoon", "\u20D0"],
])("writes the %s accent as the combining character Word uses", (accent, character) => {
expect(toXml(new MathAccent({ accent, children: [new MathRun("x")] }))).toContain(`<m:chr m:val="${character}"/>`);
});
it("writes an accent over nothing with a zero-width space, which LibreOffice needs", () => {
expect(toXml(new MathAccent({ children: [] }))).toContain('<m:e><m:r><m:t xml:space="preserve">\u200B</m:t></m:r></m:e>');
});
it("throws for an accent it doesn't know, for code that isn't type checked", () => {
// @ts-expect-error -- not an accent
expect(() => new MathAccent({ accent: "vec", children: [] })).toThrow('MathAccent: accent is "vec", which isn\'t one of "hat"');
});
it("throws for a Math in its children, which Word won't open", () => {
expect(() => new MathAccent({ children: [new Math({ children: [] })] })).toThrow("MathAccent: children holds a Math");
});
});
+105
View File
@@ -0,0 +1,105 @@
/**
* Accents over math, such as a hat, a tilde, dots or a vector's arrow.
*
* @module
*/
import { BuilderElement, type MathComponent } from "docx";
import { checkArgument, checkOneOf, createArgument, createValueElement } from "./math-elements";
/**
* An accent over math, as LaTeX writes it:
*
* - `"hat"`: x̂, `\hat` and `\widehat`;
* - `"check"`: x̌, `\check`;
* - `"tilde"`: x̃, `\tilde` and `\widetilde`;
* - `"acute"`: x́, `\acute`;
* - `"grave"`: x̀, `\grave`;
* - `"dot"`: ẋ, `\dot`;
* - `"doubleDot"`: ẍ, `\ddot`;
* - `"tripleDot"`: x⃛, `\dddot`;
* - `"breve"`: x̆, `\breve`;
* - `"bar"`: x̅, `\bar`;
* - `"ring"`: x̊, `\mathring`;
* - `"rightArrow"`: x⃗, `\vec` and `\overrightarrow`;
* - `"leftArrow"`: x⃖, `\overleftarrow`;
* - `"leftRightArrow"`: x⃡, `\overleftrightarrow`;
* - `"rightHarpoon"`: x⃑, `\overrightharpoon`;
* - `"leftHarpoon"`: x⃐, `\overleftharpoon`.
*/
export type MathAccentName =
| "hat"
| "check"
| "tilde"
| "acute"
| "grave"
| "dot"
| "doubleDot"
| "tripleDot"
| "breve"
| "bar"
| "ring"
| "rightArrow"
| "leftArrow"
| "leftRightArrow"
| "rightHarpoon"
| "leftHarpoon";
/**
* Options for {@link MathAccent}.
*/
export type MathAccentOptions = {
/**
* The accent.
* @default "hat"
*/
readonly accent?: MathAccentName;
/** What the accent goes over */
readonly children: readonly MathComponent[];
};
// The combining characters of Word's accents
const ACCENTS: Readonly<Record<MathAccentName, string>> = {
hat: "\u0302",
check: "\u030C",
tilde: "\u0303",
acute: "\u0301",
grave: "\u0300",
dot: "\u0307",
doubleDot: "\u0308",
tripleDot: "\u20DB",
breve: "\u0306",
bar: "\u0305",
ring: "\u030A",
rightArrow: "\u20D7",
leftArrow: "\u20D6",
leftRightArrow: "\u20E1",
rightHarpoon: "\u20D1",
leftHarpoon: "\u20D0",
};
/**
* An accent over math (`m:acc`), such as a hat, a tilde, dots or a vector's arrow, as LaTeX's `\hat`, `\tilde`,
* `\dot` and `\vec`. Word stretches the accent over what it goes over.
*
* For a line over or under math, as LaTeX's `\overline` and `\underline`, use a `MathBar`.
*
* @example
* ```typescript
* new MathAccent({ accent: "rightArrow", children: [new MathRun("v")] });
* ```
*/
export class MathAccent extends BuilderElement {
public constructor({ accent = "hat", children }: MathAccentOptions) {
checkOneOf("MathAccent", "accent", accent, Object.keys(ACCENTS));
checkArgument("MathAccent", "children", children);
super({
name: "m:acc",
children: [
new BuilderElement({ name: "m:accPr", children: [createValueElement("m:chr", ACCENTS[accent])] }),
createArgument(children),
],
});
}
}
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import xml from "xml";
import { Formatter } from "@export/formatter";
import { Math, MathRun } from "docx";
import { MathBar } from "./math-bar";
const toXml = (component: MathBar): string => xml(new Formatter().format(component));
describe("MathBar", () => {
it("puts a line above its children by default, writing the position, as the schema's default is below", () => {
expect(toXml(new MathBar({ children: [new MathRun("AB")] }))).toBe(
'<m:bar><m:barPr><m:pos m:val="top"/></m:barPr><m:e><m:r><m:t>AB</m:t></m:r></m:e></m:bar>',
);
});
it("puts a line below its children", () => {
expect(toXml(new MathBar({ position: "below", children: [new MathRun("x")] }))).toContain('<m:pos m:val="bot"/>');
});
it("writes a line over nothing with a zero-width space", () => {
expect(toXml(new MathBar({ children: [] }))).toContain('<m:t xml:space="preserve">\u200B</m:t>');
});
it("throws for a position it doesn't know, and for a Math in its children", () => {
// @ts-expect-error -- not a position
expect(() => new MathBar({ position: "top", children: [] })).toThrow(
'MathBar: position is "top", which isn\'t one of "above", "below"',
);
expect(() => new MathBar({ children: [new Math({ children: [] })] })).toThrow("MathBar: children holds a Math");
});
});
+51
View File
@@ -0,0 +1,51 @@
/**
* Lines over or under math, such as LaTeX's `\overline` and `\underline`.
*
* @module
*/
import { BuilderElement, type MathComponent } from "docx";
import { checkArgument, checkOneOf, createArgument, createValueElement } from "./math-elements";
/** Whether something goes above or below the math it is on */
export type MathPosition = "above" | "below";
export const POSITIONS: readonly MathPosition[] = ["above", "below"];
/**
* Options for {@link MathBar}.
*/
export type MathBarOptions = {
/**
* Whether the line goes above or below.
* @default "above"
*/
readonly position?: MathPosition;
/** What the line goes over or under */
readonly children: readonly MathComponent[];
};
/**
* A line over or under math (`m:bar`), as LaTeX's `\overline` and `\underline`, as long as what it goes over.
*
* @example
* ```typescript
* new MathBar({ children: [new MathRun("AB")] });
* new MathBar({ position: "below", children: [new MathRun("x")] });
* ```
*/
export class MathBar extends BuilderElement {
public constructor({ position = "above", children }: MathBarOptions) {
checkOneOf("MathBar", "position", position, POSITIONS);
checkArgument("MathBar", "children", children);
super({
name: "m:bar",
children: [
// Written either way, as the schema's default is below, and Word's own bar is above
new BuilderElement({ name: "m:barPr", children: [createValueElement("m:pos", position === "above" ? "top" : "bot")] }),
createArgument(children),
],
});
}
}
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import xml from "xml";
import { Formatter } from "@export/formatter";
import { Math, MathRun } from "docx";
import { MathBox } from "./math-box";
const toXml = (component: MathBox): string => xml(new Formatter().format(component));
describe("MathBox", () => {
it("draws a box around its children, with no properties, as all four sides are drawn by default", () => {
expect(toXml(new MathBox({ children: [new MathRun("x")] }))).toBe("<m:borderBox><m:e><m:r><m:t>x</m:t></m:r></m:e></m:borderBox>");
});
it("hides the sides left out, in the schema's order", () => {
expect(toXml(new MathBox({ borders: ["left", "top"], children: [new MathRun("x")] }))).toContain(
'<m:borderBoxPr><m:hideBot m:val="1"/><m:hideRight m:val="1"/></m:borderBoxPr>',
);
});
it("strikes lines through it, with no box, as LaTeX's \\cancel does", () => {
expect(toXml(new MathBox({ borders: [], strikes: ["diagonalDown", "diagonalUp"], children: [new MathRun("x")] }))).toBe(
"<m:borderBox><m:borderBoxPr>" +
'<m:hideTop m:val="1"/><m:hideBot m:val="1"/><m:hideLeft m:val="1"/><m:hideRight m:val="1"/>' +
'<m:strikeBLTR m:val="1"/><m:strikeTLBR m:val="1"/>' +
"</m:borderBoxPr><m:e><m:r><m:t>x</m:t></m:r></m:e></m:borderBox>",
);
});
it("strikes horizontal and vertical lines", () => {
expect(toXml(new MathBox({ strikes: ["vertical", "horizontal"], children: [] }))).toContain(
'<m:borderBoxPr><m:strikeH m:val="1"/><m:strikeV m:val="1"/></m:borderBoxPr>',
);
});
it("throws for a side or strike it doesn't know, and for a Math in its children", () => {
// @ts-expect-error -- not a side
expect(() => new MathBox({ borders: ["bot"], children: [] })).toThrow('MathBox: borders is "bot"');
// @ts-expect-error -- not a strike
expect(() => new MathBox({ strikes: ["strikeH"], children: [] })).toThrow('MathBox: strikes is "strikeH"');
expect(() => new MathBox({ children: [new Math({ children: [] })] })).toThrow("MathBox: children holds a Math");
});
});
+85
View File
@@ -0,0 +1,85 @@
/**
* Boxes around math, and lines struck through it, such as LaTeX's `\boxed` and `\cancel`.
*
* @module
*/
// cspell:ignore ncel
import { BuilderElement, type MathComponent } from "docx";
import { checkArgument, checkOneOf, createArgument, createValueElement } from "./math-elements";
/** A side of a box */
export type MathBoxSide = "top" | "bottom" | "left" | "right";
/**
* A line struck through a box:
*
* - `"horizontal"`: across its middle;
* - `"vertical"`: down its middle;
* - `"diagonalUp"`: from its bottom left corner to its top right, as LaTeX's `\cancel`;
* - `"diagonalDown"`: from its top left corner to its bottom right, as `\bcancel`.
*/
export type MathBoxStrike = "horizontal" | "vertical" | "diagonalUp" | "diagonalDown";
/**
* Options for {@link MathBox}.
*/
export type MathBoxOptions = {
/** What goes in the box */
readonly children: readonly MathComponent[];
/**
* The sides of the box that are drawn. `[]` draws none, for lines struck through math with no box.
* @default ["top", "bottom", "left", "right"]
*/
readonly borders?: readonly MathBoxSide[];
/**
* Lines struck through the box, such as `["diagonalUp"]` to cancel a term.
* @default []
*/
readonly strikes?: readonly MathBoxStrike[];
};
const SIDES: Readonly<Record<MathBoxSide, string>> = { top: "m:hideTop", bottom: "m:hideBot", left: "m:hideLeft", right: "m:hideRight" };
const STRIKES: Readonly<Record<MathBoxStrike, string>> = {
horizontal: "m:strikeH",
vertical: "m:strikeV",
diagonalUp: "m:strikeBLTR",
diagonalDown: "m:strikeTLBR",
};
/**
* A box around math (`m:borderBox`), as LaTeX's `\boxed`, with lines struck through it, as `\cancel`, `\bcancel` and
* `\xcancel`. Any of its sides can be left out.
*
* @example
* ```typescript
* new MathBox({ children: [new MathRun("E=mc²")] });
* new MathBox({ borders: [], strikes: ["diagonalUp"], children: [new MathRun("x")] });
* ```
*/
export class MathBox extends BuilderElement {
public constructor({ children, borders = ["top", "bottom", "left", "right"], strikes = [] }: MathBoxOptions) {
borders.forEach((side) => checkOneOf("MathBox", "borders", side, Object.keys(SIDES)));
strikes.forEach((strike) => checkOneOf("MathBox", "strikes", strike, Object.keys(STRIKES)));
checkArgument("MathBox", "children", children);
// In the schema's order, which is the order of the records
const properties = [
...Object.entries(SIDES)
.filter(([side]) => !borders.includes(side as MathBoxSide))
.map(([, name]) => createValueElement(name, 1)),
...Object.entries(STRIKES)
.filter(([strike]) => strikes.includes(strike as MathBoxStrike))
.map(([, name]) => createValueElement(name, 1)),
];
super({
name: "m:borderBox",
children: [
...(properties.length === 0 ? [] : [new BuilderElement({ name: "m:borderBoxPr", children: properties })]),
createArgument(children),
],
});
}
}
+65
View File
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import xml from "xml";
import { Formatter } from "@export/formatter";
import { Math, MathRun } from "docx";
import { MathBrace } from "./math-brace";
const toXml = (component: MathBrace): string => xml(new Formatter().format(component));
const e = "<m:e><m:r><m:t>a+b</m:t></m:r></m:e>";
describe("MathBrace", () => {
it("puts a curly brace above its children by default, lined up with the text by its bottom", () => {
expect(toXml(new MathBrace({ children: [new MathRun("a+b")] }))).toBe(
'<m:groupChr><m:groupChrPr><m:chr m:val="⏞"/><m:pos m:val="top"/><m:vertJc m:val="bot"/></m:groupChrPr>' + `${e}</m:groupChr>`,
);
});
it("puts a brace below, lined up by its top", () => {
expect(toXml(new MathBrace({ position: "below", children: [new MathRun("a+b")] }))).toBe(
'<m:groupChr><m:groupChrPr><m:chr m:val="⏟"/><m:pos m:val="bot"/><m:vertJc m:val="top"/></m:groupChrPr>' + `${e}</m:groupChr>`,
);
});
it.each([
["curly", "above", "⏞"],
["curly", "below", "⏟"],
["square", "above", "⎴"],
["square", "below", "⎵"],
["round", "above", "⏜"],
["round", "below", "⏝"],
] as const)("draws a %s brace %s as %s", (brace, position, character) => {
expect(toXml(new MathBrace({ brace, position, children: [] }))).toContain(`<m:chr m:val="${character}"/>`);
});
it("puts a label above a brace above, in a limit, as Word writes it", () => {
expect(toXml(new MathBrace({ children: [new MathRun("a+b")], label: [new MathRun("n")] }))).toBe(
"<m:limUpp><m:e><m:groupChr>" +
'<m:groupChrPr><m:chr m:val="⏞"/><m:pos m:val="top"/><m:vertJc m:val="bot"/></m:groupChrPr>' +
`${e}</m:groupChr></m:e><m:lim><m:r><m:t>n</m:t></m:r></m:lim></m:limUpp>`,
);
});
it("puts a label below a brace below", () => {
const written = toXml(new MathBrace({ position: "below", children: [new MathRun("a+b")], label: [new MathRun("n")] }));
expect(written).toMatch(/^<m:limLow><m:e><m:groupChr>/);
expect(written).toMatch(/<m:lim><m:r><m:t>n<\/m:t><\/m:r><\/m:lim><\/m:limLow>$/);
});
it("writes an empty label with a zero-width space", () => {
expect(toXml(new MathBrace({ children: [], label: [] }))).toContain(
'<m:lim><m:r><m:t xml:space="preserve">\u200B</m:t></m:r></m:lim>',
);
});
it("throws for a position or brace it doesn't know, and for a Math in its children or label", () => {
// @ts-expect-error -- not a position
expect(() => new MathBrace({ position: "top", children: [] })).toThrow('MathBrace: position is "top"');
// @ts-expect-error -- not a brace
expect(() => new MathBrace({ brace: "angled", children: [] })).toThrow('MathBrace: brace is "angled"');
expect(() => new MathBrace({ children: [new Math({ children: [] })] })).toThrow("MathBrace: children holds a Math");
expect(() => new MathBrace({ children: [], label: [new Math({ children: [] })] })).toThrow("MathBrace: label holds a Math");
});
});
+96
View File
@@ -0,0 +1,96 @@
/**
* Braces over or under math, with a label, such as LaTeX's `\overbrace` and `\underbrace`.
*
* @module
*/
// cspell:ignore underparen
import { BuilderElement, type MathComponent, createMathBase } from "docx";
import { type MathPosition, POSITIONS } from "./math-bar";
import { checkArgument, checkOneOf, createArgument, createNamedArgument, createValueElement } from "./math-elements";
/**
* The shape of a brace:
*
* - `"curly"`: ⏞ and ⏟, as LaTeX's `\overbrace` and `\underbrace`;
* - `"square"`: ⎴ and ⎵, as `\overbracket` and `\underbracket`;
* - `"round"`: ⏜ and ⏝, as `\overparen` and `\underparen`.
*/
export type MathBraceShape = "curly" | "square" | "round";
/**
* Options for {@link MathBrace}.
*/
export type MathBraceOptions = {
/**
* Whether the brace goes above or below.
* @default "above"
*/
readonly position?: MathPosition;
/**
* The shape of the brace.
* @default "curly"
*/
readonly brace?: MathBraceShape;
/** What the brace goes over or under */
readonly children: readonly MathComponent[];
/** A label on the brace's other side, such as `n times` */
readonly label?: readonly MathComponent[];
};
const BRACES: Readonly<Record<MathBraceShape, Readonly<Record<MathPosition, string>>>> = {
curly: { above: "⏞", below: "⏟" },
square: { above: "⎴", below: "⎵" },
round: { above: "⏜", below: "⏝" },
};
/**
* A brace over or under math (`m:groupChr`), as long as what it goes over, as LaTeX's `\overbrace` and
* `\underbrace`. A label goes on the brace's other side, as Word writes it: in a limit above (`m:limUpp`) or below
* (`m:limLow`).
*
* @example
* ```typescript
* new MathBrace({
* position: "below",
* children: [new MathRun("1+2+⋯+n")],
* label: [new MathRun("n terms")],
* });
* ```
*/
export class MathBrace extends BuilderElement {
public constructor({ position = "above", brace = "curly", children, label }: MathBraceOptions) {
checkOneOf("MathBrace", "position", position, POSITIONS);
checkOneOf("MathBrace", "brace", brace, Object.keys(BRACES));
checkArgument("MathBrace", "children", children);
if (label !== undefined) {
checkArgument("MathBrace", "label", label);
}
const above = position === "above";
const group = {
name: "m:groupChr",
children: [
new BuilderElement({
name: "m:groupChrPr",
children: [
createValueElement("m:chr", BRACES[brace][position]),
createValueElement("m:pos", above ? "top" : "bot"),
// Lines the brace up with the text by its side nearest what it goes over
createValueElement("m:vertJc", above ? "bot" : "top"),
],
}),
createArgument(children),
],
};
super(
label === undefined
? group
: {
name: above ? "m:limUpp" : "m:limLow",
children: [createMathBase({ children: [new BuilderElement(group)] }), createNamedArgument("m:lim", label)],
},
);
}
}
+10 -5
View File
@@ -4,7 +4,7 @@
*
* @module
*/
import { BuilderElement, type MathComponent, MathRun, Math as OfficeMath, Paragraph, Run, type XmlComponent, createMathBase } from "docx";
import { BuilderElement, type MathComponent, MathRun, Math as OfficeMath, Paragraph, Run, type XmlComponent } from "docx";
/** The options of a {@link BuilderElement}, to build an element before its class calls `super` */
export type ElementOptions = {
@@ -65,11 +65,16 @@ export const checkOneOf = (owner: string, option: string, value: string, allowed
};
/**
* An argument (`m:e`). An empty one gets a zero-width space, as LibreOffice can't read an equation with an empty
* argument, and draws "¿" in its place.
* An argument of any name, such as a limit (`m:lim`). An empty one gets a zero-width space, as LibreOffice can't read
* an equation with an empty argument, and draws "¿" in its place.
*/
export const createArgument = (children: readonly MathComponent[]): XmlComponent =>
createMathBase({ children: children.length === 0 ? [new MathRun("​")] : children });
export const createNamedArgument = (name: string, children: readonly MathComponent[]): XmlComponent =>
new BuilderElement({ name, children: children.length === 0 ? [new MathRun("\u200B")] : children });
/**
* An argument (`m:e`). An empty one gets a zero-width space, as {@link createNamedArgument} says.
*/
export const createArgument = (children: readonly MathComponent[]): XmlComponent => createNamedArgument("m:e", children);
/**
* Brackets (`m:d`) around arguments, with a separator between them. They grow with their content unless `grow` is
+74
View File
@@ -0,0 +1,74 @@
import { describe, expect, it } from "vitest";
import xml from "xml";
import { Formatter } from "@export/formatter";
import { Math, MathRun } from "docx";
import { LARGE_OPERATORS, MathLargeOperator, type MathLargeOperatorName } from "./math-large-operator";
const toXml = (component: MathLargeOperator): string => xml(new Formatter().format(component));
describe("MathLargeOperator", () => {
it("writes the operator with its limits above and below, and what it applies to", () => {
expect(
toXml(
new MathLargeOperator({
operator: "product",
subScript: [new MathRun("i=1")],
superScript: [new MathRun("n")],
children: [new MathRun("i")],
}),
),
).toBe(
'<m:nary><m:naryPr><m:chr m:val="∏"/><m:limLoc m:val="undOvr"/></m:naryPr>' +
"<m:sub><m:r><m:t>i=1</m:t></m:r></m:sub><m:sup><m:r><m:t>n</m:t></m:r></m:sup>" +
"<m:e><m:r><m:t>i</m:t></m:r></m:e></m:nary>",
);
});
it("hides the limits not given, and writes them empty, as the schema needs both", () => {
expect(toXml(new MathLargeOperator({ operator: "union", children: [new MathRun("A")] }))).toBe(
'<m:nary><m:naryPr><m:chr m:val="⋃"/><m:limLoc m:val="undOvr"/><m:subHide m:val="1"/><m:supHide m:val="1"/></m:naryPr>' +
"<m:sub/><m:sup/><m:e><m:r><m:t>A</m:t></m:r></m:e></m:nary>",
);
});
it.each(Object.entries(LARGE_OPERATORS) as readonly (readonly [MathLargeOperatorName, string])[])(
"writes the %s as %s, with its limits where Word puts them",
(operator, character) => {
const written = toXml(new MathLargeOperator({ operator, children: [] }));
expect(written).toContain(`<m:chr m:val="${character}"/>`);
expect(written).toContain(`<m:limLoc m:val="${operator.endsWith("ntegral") ? "subSup" : "undOvr"}"/>`);
},
);
it("puts the limits where it is told", () => {
expect(toXml(new MathLargeOperator({ operator: "sum", limits: "side", children: [] }))).toContain('<m:limLoc m:val="subSup"/>');
expect(toXml(new MathLargeOperator({ operator: "integral", limits: "aboveBelow", children: [] }))).toContain(
'<m:limLoc m:val="undOvr"/>',
);
});
it("writes an operator applied to nothing with a zero-width space", () => {
expect(toXml(new MathLargeOperator({ operator: "sum", children: [] }))).toContain(
'<m:e><m:r><m:t xml:space="preserve">\u200B</m:t></m:r></m:e>',
);
});
it("throws for an operator or limits it doesn't know, and for a Math in any argument", () => {
const math = new Math({ children: [] });
// @ts-expect-error -- not an operator
expect(() => new MathLargeOperator({ operator: "prod", children: [] })).toThrow('MathLargeOperator: operator is "prod"');
// @ts-expect-error -- not a position
expect(() => new MathLargeOperator({ operator: "sum", limits: "undOvr", children: [] })).toThrow(
'MathLargeOperator: limits is "undOvr"',
);
expect(() => new MathLargeOperator({ operator: "sum", children: [math] })).toThrow("MathLargeOperator: children holds a Math");
expect(() => new MathLargeOperator({ operator: "sum", subScript: [math], children: [] })).toThrow(
"MathLargeOperator: subScript holds a Math",
);
expect(() => new MathLargeOperator({ operator: "sum", superScript: [math], children: [] })).toThrow(
"MathLargeOperator: superScript holds a Math",
);
});
});
+151
View File
@@ -0,0 +1,151 @@
/**
* Large operators with limits, such as products, unions and contour integrals, as well as sums and integrals.
*
* @module
*/
// cspell:ignore bigodot bigoplus bigotimes bigsqcup biguplus coproduct
import {
BuilderElement,
type MathComponent,
type MathLimitsPosition,
createMathNAryProperties,
createMathSubScriptElement,
createMathSuperScriptElement,
} from "docx";
import { checkArgument, checkOneOf, createArgument } from "./math-elements";
/**
* A large operator, as LaTeX writes it:
*
* - `"sum"`: ∑, `\sum`;
* - `"product"`: ∏, `\prod`;
* - `"coproduct"`: ∐, `\coprod`;
* - `"union"`: ⋃, `\bigcup`;
* - `"intersection"`: ⋂, `\bigcap`;
* - `"squareUnion"`: ⨆, `\bigsqcup`;
* - `"multisetUnion"`: ⨄, `\biguplus`;
* - `"logicalOr"`: ⋁, `\bigvee`;
* - `"logicalAnd"`: ⋀, `\bigwedge`;
* - `"directSum"`: ⨁, `\bigoplus`;
* - `"tensorProduct"`: ⨂, `\bigotimes`;
* - `"circledDot"`: ⨀, `\bigodot`;
* - `"integral"`: ∫, `\int`;
* - `"doubleIntegral"`: ∬, `\iint`;
* - `"tripleIntegral"`: ∭, `\iiint`;
* - `"quadrupleIntegral"`: ⨌, `\iiiint`;
* - `"contourIntegral"`: ∮, `\oint`;
* - `"surfaceIntegral"`: ∯, `\oiint`;
* - `"volumeIntegral"`: ∰, `\oiiint`.
*/
export type MathLargeOperatorName =
| "sum"
| "product"
| "coproduct"
| "union"
| "intersection"
| "squareUnion"
| "multisetUnion"
| "logicalOr"
| "logicalAnd"
| "directSum"
| "tensorProduct"
| "circledDot"
| "integral"
| "doubleIntegral"
| "tripleIntegral"
| "quadrupleIntegral"
| "contourIntegral"
| "surfaceIntegral"
| "volumeIntegral";
/**
* Options for {@link MathLargeOperator}.
*/
export type MathLargeOperatorOptions = {
/** The operator */
readonly operator: MathLargeOperatorName;
/** What the operator applies to, such as the terms of a sum */
readonly children: readonly MathComponent[];
/** The lower limit, such as `i=1` */
readonly subScript?: readonly MathComponent[];
/** The upper limit, such as `n` */
readonly superScript?: readonly MathComponent[];
/**
* Where the limits go: above and below the operator, or to its right.
* @default "side" for integrals, and "aboveBelow" for the others, as Word puts them
*/
readonly limits?: MathLimitsPosition;
};
export const LARGE_OPERATORS: Readonly<Record<MathLargeOperatorName, string>> = {
sum: "∑",
product: "∏",
coproduct: "∐",
union: "⋃",
intersection: "⋂",
squareUnion: "⨆",
multisetUnion: "⨄",
logicalOr: "⋁",
logicalAnd: "⋀",
directSum: "⨁",
tensorProduct: "⨂",
circledDot: "⨀",
integral: "∫",
doubleIntegral: "∬",
tripleIntegral: "∭",
quadrupleIntegral: "⨌",
contourIntegral: "∮",
surfaceIntegral: "∯",
volumeIntegral: "∰",
};
const LIMITS: readonly MathLimitsPosition[] = ["aboveBelow", "side"];
/**
* A large operator with limits (`m:nary`), such as ∏, ⋃ or ∮, as LaTeX's `\prod`, `\bigcup` and `\oint`, over what
* it applies to. `MathSum` and `MathIntegral` are two of these.
*
* @example
* ```typescript
* new MathLargeOperator({
* operator: "product",
* subScript: [new MathRun("i=1")],
* superScript: [new MathRun("n")],
* children: [new MathRun("i")],
* });
* ```
*/
export class MathLargeOperator extends BuilderElement {
public constructor({ operator, children, subScript, superScript, limits }: MathLargeOperatorOptions) {
checkOneOf("MathLargeOperator", "operator", operator, Object.keys(LARGE_OPERATORS));
if (limits !== undefined) {
checkOneOf("MathLargeOperator", "limits", limits, LIMITS);
}
checkArgument("MathLargeOperator", "children", children);
if (subScript !== undefined) {
checkArgument("MathLargeOperator", "subScript", subScript);
}
if (superScript !== undefined) {
checkArgument("MathLargeOperator", "superScript", superScript);
}
const side = limits === undefined ? operator.endsWith("ntegral") : limits === "side";
super({
name: "m:nary",
children: [
createMathNAryProperties({
accent: LARGE_OPERATORS[operator],
hasSubScript: subScript !== undefined,
hasSuperScript: superScript !== undefined,
limitLocationVal: side ? "subSup" : "undOvr",
}),
// The schema needs both limits, so a hidden one is written empty
createMathSubScriptElement({ children: subScript ?? [] }),
createMathSuperScriptElement({ children: superScript ?? [] }),
createArgument(children),
],
});
}
}
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import xml from "xml";
import { Formatter } from "@export/formatter";
import { Math, MathRun } from "docx";
import { MathPhantom } from "./math-phantom";
const toXml = (component: MathPhantom): string => xml(new Formatter().format(component));
describe("MathPhantom", () => {
it("hides its children, which still take up their room, by default", () => {
expect(toXml(new MathPhantom({ children: [new MathRun("x")] }))).toBe(
'<m:phant><m:phantPr><m:show m:val="0"/></m:phantPr><m:e><m:r><m:t>x</m:t></m:r></m:e></m:phant>',
);
});
it("gives them no width, height or depth, as LaTeX's \\vphantom, \\hphantom and \\smash do", () => {
expect(toXml(new MathPhantom({ width: false, children: [] }))).toContain(
'<m:phantPr><m:show m:val="0"/><m:zeroWid m:val="1"/></m:phantPr>',
);
expect(toXml(new MathPhantom({ visible: true, height: false, depth: false, children: [] }))).toContain(
'<m:phantPr><m:show m:val="1"/><m:zeroAsc m:val="1"/><m:zeroDesc m:val="1"/></m:phantPr>',
);
});
it("throws for a Math in its children", () => {
expect(() => new MathPhantom({ children: [new Math({ children: [] })] })).toThrow("MathPhantom: children holds a Math");
});
});
+74
View File
@@ -0,0 +1,74 @@
/**
* Phantoms: math that takes up room without being seen, or is seen without taking up room, such as LaTeX's
* `\phantom` and `\smash`.
*
* @module
*/
import { BuilderElement, type MathComponent } from "docx";
import { checkArgument, createArgument, createValueElement } from "./math-elements";
/**
* Options for {@link MathPhantom}.
*/
export type MathPhantomOptions = {
/** The math */
readonly children: readonly MathComponent[];
/**
* Whether the math is seen (`m:show`).
* @default false
*/
readonly visible?: boolean;
/**
* Whether it takes up its width. False gives it none (`m:zeroWid`), as LaTeX's `\vphantom`.
* @default true
*/
readonly width?: boolean;
/**
* Whether it takes up its height above the line. False gives it none (`m:zeroAsc`), as LaTeX's `\hphantom` and
* `\smash`.
* @default true
*/
readonly height?: boolean;
/**
* Whether it takes up its depth below the line. False gives it none (`m:zeroDesc`), as LaTeX's `\hphantom` and
* `\smash`.
* @default true
*/
readonly depth?: boolean;
};
/**
* A phantom (`m:phant`): math that takes up room without being seen, as LaTeX's `\phantom`, to leave space for it or
* line things up with it. Or math that is seen but takes up no room, or less, as `\smash`.
*
* @example
* ```typescript
* // As much space as "x+y" takes up
* new MathPhantom({ children: [new MathRun("x+y")] });
*
* // A tall fraction that doesn't push its line apart
* new MathPhantom({ visible: true, height: false, depth: false, children: [fraction] });
* ```
*/
export class MathPhantom extends BuilderElement {
public constructor({ children, visible = false, width = true, height = true, depth = true }: MathPhantomOptions) {
checkArgument("MathPhantom", "children", children);
super({
name: "m:phant",
children: [
new BuilderElement({
name: "m:phantPr",
children: [
createValueElement("m:show", visible ? 1 : 0),
...(width ? [] : [createValueElement("m:zeroWid", 1)]),
...(height ? [] : [createValueElement("m:zeroAsc", 1)]),
...(depth ? [] : [createValueElement("m:zeroDesc", 1)]),
],
}),
createArgument(children),
],
});
}
}
+57 -1
View File
@@ -3,12 +3,19 @@ import xml from "xml";
import { type Element, xml2js } from "xml-js";
import { Formatter } from "@export/formatter";
import { Math, type MathComponent, MathFraction, MathRun, MathSuperScript } from "docx";
import { Math, type MathComponent, MathFraction, MathIntegral, MathRun, MathSum, MathSuperScript } from "docx";
import { latexToMath } from "./latex-to-math";
import { MathAccent } from "./math-accent";
import { MathBar } from "./math-bar";
import { MathBox } from "./math-box";
import { MathBrace } from "./math-brace";
import { MathBrackets } from "./math-brackets";
import { MathCases } from "./math-cases";
import { MathEquationArray } from "./math-equation-array";
import { MathLargeOperator } from "./math-large-operator";
import { MathMatrix, type MathMatrixBrackets } from "./math-matrix";
import { MathPhantom } from "./math-phantom";
// @ts-expect-error -- Vite reads the schema as text, which TypeScript has no type for
import mathSchema from "../../ooxml-schemas/ISO-IEC29500-4_2016/shared-math.xsd?raw";
@@ -103,6 +110,22 @@ const problemsOf = (children: readonly MathComponent[]): readonly string[] => {
const run = (text: string): MathRun => new MathRun(text);
const cell = (text: string): readonly MathComponent[] => [run(text)];
// LaTeX of every kind latexToMath reads, as the demo has it
const LATEX: readonly string[] = [
"x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\quad \\sqrt[3]{x} \\quad \\binom{n}{k} \\quad \\nicefrac12 \\quad {a \\atop b}",
"{}^{14}_{6}\\mathrm{C} \\quad f''(x) \\quad x_i^2 \\quad a \\& b \\# c",
"\\sum_{i=1}^{n} i^2 \\quad \\int\\limits_0^1 f(x)\\,dx \\quad \\bigcup_{i} A_i \\quad \\oint",
"\\sin^2\\theta \\quad \\lim_{h \\to 0} \\frac{1}{h} \\quad \\sup_a^b f \\quad \\operatorname*{arg\\,max}_x f \\quad a \\pmod{n}",
"\\left\\langle \\psi \\middle| \\phi \\right\\rangle \\left( a \\middle| b \\middle/ c \\right) \\left. x \\right|",
"\\hat{x} \\vec{v} \\overline{AB} \\underline{x} \\overbrace{a}^{n} \\underbrace{b}_{m} \\overset{!}{=} \\xrightarrow[g]{f}",
"\\boxed{x} \\cancel{y} \\xcancel{z} \\phantom{x} \\smash[t]{y} \\vphantom{z}",
"\\mathbb{R} \\mathbf{\\mathcal{A}} \\boldsymbol{\\alpha} \\Gamma \\text{if $x$ then} \\not\\in",
"\\begin{pmatrix} 1 & 2 \\\\ 3 \\end{pmatrix} \\begin{array}{lc} a & b \\end{array} \\sum_{\\substack{i \\\\ j}} a",
"|x| = \\begin{cases} x & \\text{if } x \\ge 0 \\\\ -x \\end{cases} \\begin{rcases} a \\end{rcases}",
"\\begin{align} y &= mx + b \\tag{1} \\\\ y' &= m \\end{align}",
"a &= b \\\\ &= c \\tag{2}",
];
const BRACKETS: readonly MathMatrixBrackets[] = ["none", "round", "square", "curly", "angled", "verticalBars", "doubleVerticalBars"];
const EQUATIONS: readonly (readonly [string, () => readonly MathComponent[]])[] = [
@@ -155,6 +178,39 @@ const EQUATIONS: readonly (readonly [string, () => readonly MathComponent[]])[]
}),
],
],
[
"runs in every style and alphabet, literal, and as normal text",
() => [
new MathRun({ text: "R", literal: true, script: "doubleStruck", style: "bold" }),
new MathRun({ text: "&", literal: true, normalText: true }),
new MathRun({ text: "x", style: "boldItalic" }),
],
],
[
"fractions of every type, and sums and integrals with their limits either way",
() => [
...(["stacked", "skewed", "linear", "noBar"] as const).map(
(type) => new MathFraction({ numerator: cell("a"), denominator: cell("b"), type }),
),
new MathSum({ children: cell("i"), subScript: cell("i"), limits: "side" }),
new MathIntegral({ children: cell("x"), superScript: cell("1"), limits: "aboveBelow" }),
],
],
[
"accents, bars, braces with and without labels, boxes, phantoms and large operators",
() => [
new MathAccent({ accent: "doubleDot", children: cell("x") }),
new MathBar({ position: "below", children: [] }),
new MathBrace({ children: cell("a") }),
new MathBrace({ position: "below", brace: "square", children: cell("a"), label: cell("n") }),
new MathBrace({ label: [], children: [] }),
new MathBox({ children: cell("x") }),
new MathBox({ borders: ["top"], strikes: ["horizontal", "vertical", "diagonalUp", "diagonalDown"], children: cell("x") }),
new MathPhantom({ visible: true, width: false, height: false, depth: false, children: cell("x") }),
new MathLargeOperator({ operator: "product", subScript: cell("i"), superScript: cell("n"), limits: "side", children: [] }),
],
],
...LATEX.map((latex) => [`the LaTeX ${latex}`, () => latexToMath(latex)] as const),
[
"everything inside everything",
() => [