1# OpenType mathematical fonts23Branch: `codex/opentype-math-fonts`. This branch is not a published release.45`formula(..., math_font="XITS Math")` selects an installed OpenType math font.6A font file path works on native hosts and with fonts supplied through the7in-memory/WASM host. Paths are relative to the defining `.lay` module (or8`.lcss` stylesheet). `math_font` also inherits from the canvas, text, span,9plot, and plot style. Use raw DSL strings for LaTeX, especially when mhchem10contains embedded `$...$` expressions.1112```lay13page=canvas(size=(160mm,60mm),math_font="XITS Math")14page.add(formula(r"\ce{A <=>[{forward}][{reverse}] B}",font_size=16pt))15```1617The default `ratex-katex` backend is retained. The OpenType backend reuses the18RaTeX parser and LayMesh exporters, but obtains glyphs, advances, math19constants, italic corrections, accent attachments, script kerns, stretch20variants, and connector assemblies from the selected font. It never21substitutes a KaTeX face for an explicitly selected math font.2223Covered constructions include fractions/binomials, continued fractions,24scripts, indexed roots, operators and limits, `left/right/middle`, matrices,25arrays with solid/dashed rules, aligned equations and tags, commutative26diagrams, labelled arrows, braces/brackets, accents, enclosures/cancellation,27phantoms, overlap/raise commands, line breaks, math alphabets, and inline math.28RaTeX's mhchem (`ce`/`pu`) and bussproofs (`prooftree`) use the same font-aware29constructions. Proof trees support unary through quinary inference, labels,30solid/dashed/no rules, nested branches, and changing root direction.3132A font may lack a horizontal arrow assembly, and some installed STIX Two332.02 arrow recipes contain invalid terminal connectors. For horizontal34arrows and equality only, the backend then extends the shaft region of that35font's native outline while preserving its end shapes and stroke thickness.36Other finite stretch constructions use their largest native variant when37no assembly exists. Missing glyphs use the same measured vector box in every38backend and emit `W_FONT` with Unicode codepoints. Missing MATH tables, embedding39restrictions, unavailable math fonts and invalid constructions still fail explicitly.4041`mathcal` and `mathscr` currently select the same Unicode script alphabet;42font-specific GSUB stylistic-set selection is not implemented. Math alphabet43commands follow the inner-command override used by44[KaTeX](https://github.com/KaTeX/KaTeX/blob/v0.16.22/src/Options.js):45`\mathbf{\mathcal A}` is script A, not bold script A, while46`\mathcal{\mathbf A}` is bold roman A. Use `\mathbf{A1}` for bold roman47letters/digits and `\bm{\alpha x}` for bold italic symbols. Native styled48Unicode letters also retain their selected-font glyphs. XITS Math Bold49is a supplementary face with incomplete stretch coverage: algebra works,50and missing radical constructions report an error. Regular XITS Math supports51`mathbf`, `boldsymbol`, and `bm` without selecting the standalone bold face.5253## Fixed upstream corpus5455Fixtures come from [RaTeX v0.1.14](https://github.com/erweixin/RaTeX/tree/ae391d727ac615437c63c308f4538d971a84bede),56the version used by LayMesh. The original source files, SHA-256 hashes, and57MIT license are retained under `tests/math/ratex-0.1.14`:5859- Golden formulas: 1075 entries; parser comparison: 791; layout comparison: 29.60- Chemistry: 91; physics: 22; proof trees: 38.61- Additional editable domain cases: 32, under `domain-cases.json`.6263After deduplicating the overlapping primary math suites, the audit runs 193164case entries (1921 distinct formulas), four fonts, and inline/display styles:65**15,448 layout checks**. Expected parser/policy errors and real font-coverage66limits are recorded separately. Placeholder exports are not counted as correct67glyph rendering. `expected-errors.json` pins parser/policy rejections and68`expected-placeholders.json` pins missing-codepoint sequences.6970| Backend | Exportable checks | Parser/policy rejection | Exports containing placeholders |71| --- | ---: | ---: | ---: |72| KaTeX default | 3742 | 120 | 100 |73| Latin Modern Math | 3742 | 120 | 96 |74| STIX Two Math | 3742 | 120 | 34 |75| XITS Math | 3742 | 120 | 34 |7677All 91 chemistry, 22 physics, 38 proof-tree cases and 32 additional domain78cases render in every font and style. No unimplemented OpenType node remains79in the accepted corpus. Every successful OpenType render checks finite80geometry and exported outline bounds. The missing-glyph cases include CJK,81other scripts, emoji, and some symbols absent from Latin Modern Math; choosing82a math font does not give it glyphs that the file does not contain.8384The focused regressions also verify MATH-constant fault injection, assembly85parts, alphabet codepoints, text/chemistry roman forms, relative paths, inline86baselines, plot labels, accent/operator placement, proof rules/root direction,87alignment/tag placement, 30-level delimiter nesting, zero-width spacing,88cache invalidation, embedding restrictions, and explicit errors.8990OpenType partial bonds (`~`, `~-`, `~--`, `~=`, `-~-`) are native compound91constructions. A per-parser adapter retains the bond semantics from RaTeX920.1.14's mhchem token productions before their KaTeX lap/raise/tiny-hyphen93recipes expand. It delegates to the original `ce` handler, preserving the94shared recursion limit. No formula text or font name selects a special case.95The native minus outline supplies the ink endpoints, advance, axis and96thickness; the dashed row uses three horizontally shortened copies of that97outline. Every layer inherits the current math style, size and color.98This adapter is tied to the pinned upstream productions, covered by tests;99ordinary overlays and the default RaTeX backend keep their existing behavior.100101The bond tests measure actual outline endpoints and thickness in **1,280102cases**: four font files (including XITS Bold), four sizes (6–48 pt), both103formula styles, four mixed-bond spellings, and ten contexts including104superscripts, two levels of subscripts, fractions and explicit script styles.105Another 48 chain cases include the bare dashed bond, nested chemistry and106color; they verify the native axis, consistent atom/bond scale, layer spacing107and clearance from adjacent atoms. Separate parser tests preserve ordinary108ASTs and upstream recursion errors. Rendering checks cover these paths in109SVG, PDF, PNG and PPTX. Math minus and text hyphen remain distinct.110111Nested math alphabets are tested in both command orders, independently of112the real bold-letter cases. `regressions.lay` provides an enlarged, editable113comparison; `chemical-bonds.lay` adds compound bonds in different math styles.114The existing default RaTeX backend does not select its sans italic face for115`\mathsfit`; the OpenType backend selects the correct Unicode alphabet.116117## Reproduce118119```sh120mkdir -p target/opentype-math-validation121LAYMESH_MATH_AUDIT="$PWD/target/opentype-math-validation/corpus.json" \122 cargo test -p laymesh-core --test opentype_math --test opentype_math_corpus123python3 experiments/opentype-math/summarize-corpus.py \124 target/opentype-math-validation/corpus.json125cargo test -p laymesh-render --test opentype_math126cargo build -p laymesh-cli127python3 experiments/opentype-math/verify.py128.venv/bin/python experiments/opentype-math/build-atlas.py129target/debug/laymesh render experiments/opentype-math/regressions.lay \130 -o target/opentype-math-validation/regressions.png --dpi 160131target/debug/laymesh render experiments/opentype-math/chemical-bonds.lay \132 -o target/opentype-math-validation/chemical-bonds.png --dpi 180133```134135Outputs go to `target/opentype-math-validation`: the original comparison,136a four-page vector `domain-atlas.pdf`, editable `.lay` pages, SVG/PNG/PPTX137exports, PDF-derived previews, and machine-readable audit results. The atlas138builder needs PyMuPDF and Poppler. A release binary can be selected with139`--binary target/release/laymesh` for both render scripts.140141The deterministic font fixtures are unmodified Latin Modern Math 1.959,142STIX Two Math 2.02 b142, and XITS Math 1.302 regular/bold, with license notices.143They are test assets and are not bundled into distribution packages.144145## Browser corpus gallery146147The gallery retains every nonempty, noncomment entry in all eleven formula148corpus files from the pinned RaTeX v0.1.14 checkout, including duplicates:149the six primary suites above, lexer comparison (791), website mathematics150(1048), website proof trees (38), the original chemistry text fixture (103),151and the Unicode smoke-test script (18). With the 32 domain examples and 24152text fallback cases this is **4100 entries, 1961 distinct formulas, and15365,600 font/style/text-policy results**.154This scope covers the original formula corpus files; it does not claim to155display every assertion from RaTeX's Rust, platform or application unit tests.156157Previews use the shared DisplayList and Vello CPU WASM Canvas renderer, with KaTeX,158Latin Modern Math, STIX Two Math and XITS Math in inline and display styles.159With body text fallback disabled, the 15,368 distinct combinations already160present in the fixed audit must match its exact parser/policy/font-coverage161outcomes. The remaining 16,008 combinations cover supplementary formulas and162the full corpus with text fallback enabled, and check OpenType geometry without163assigning new results a pre-existing expected-error baseline.164Every original fixture and font asset is verified against its SHA-256.165The page exposes source-file positions, errors, text fallback, missing-glyph166placeholders and invalid dimensions. A successful export alone is not a167visual-quality assertion. SVG is retained only as a downloadable file export. Native RGBA references at16816 px are compared to every successful distinct WASM rendering.169Baseline guides, DPR-aware Canvas zoom, source search,170category/status/font filters, pagination and detail views support manual review.171172```sh173# First generate corpus.json using the audit command above.174cargo build -p laymesh-render --example math_gallery --release175cargo build --release --locked --target wasm32-unknown-unknown -p laymesh-wasm --no-default-features176wasm-bindgen --target web --out-dir extensions/vscode/dist/wasm target/wasm32-unknown-unknown/release/laymesh_wasm.wasm177python3 experiments/opentype-math/build-gallery.py --output target/rust-renderer-math-gallery178python3 experiments/opentype-math/serve-gallery.py --directory target/rust-renderer-math-gallery --port 8768179python3 experiments/opentype-math/verify-gallery.py --url http://100.64.0.6:8768/180```181182The server binds to the machine's Tailscale IPv4 address by default and serves183only the selected generated directory. It does not publish through Funnel.184On this development host the URL is `http://100.64.0.6:8768/`;185`?suite=chemistry` opens chemistry and `?suite=domain&q=bond&size=48`186opens the enlarged compound-bond example. `/health` reports the loaded count.187After frontend-only edits, `build-gallery.py --reuse` refreshes the page while188checking the renderer fingerprint, all prior outcomes and SVG hashes.189190191## Formula text fallback192193`math_text_fallback=true` is inherited by default. Formula `font_family`194selects literal text, independently of `math_font`. An explicit font list is195ordered and does not silently add unlisted families. A single family or file196request retains the existing ordinary-text selection and warning behavior.197198Both engines shape adjacent text runs before mathematical placement, using199actual advances, outline extents, Unicode bidi ordering and Rustybuzz shaping.200Text in scripts, fractions, chemical annotations, matrices and proof cells201uses the same flow. Exports use outlines rather than a browser-dependent text202font. Real bold/italic faces are selected by text commands; missing styles warn.203Mathematical alphabet commands continue to use the selected math font.204205```lay206page=canvas(size=(140mm,50mm),math_font="XITS Math",207 font_family=["Noto Serif","Noto Serif CJK SC"])208page.add(formula(r"\text{你好,世界!}\quad E=mc^2",font_size=16pt))209```210211The gallery defaults to enabled text fallback with eight pinned, renamed Noto212subsets, and has a switch to disable it. This isolates test results from host213font installation. Details disclose actual family, face, weight and glyph214count. `/sources/text-fonts-manifest.json` retains input and output hashes;215[font fixtures](../../tests/fonts/text/README.md) document rebuilding and licenses.216The four math font files remain unchanged. Color bitmap emoji are unsupported217by this outline-only text flow. Missing text or math glyphs use vector boxes218with warnings, including when text fallback is disabled or its font list is219exhausted; adjacent supported glyphs and mathematical structure remain visible.220221The default KaTeX route uses the optional measured-text hook in the222[muxkin/RaTeX fork](https://github.com/muxkin/RaTeX/blob/9e03b1c0f365a15f51e68649311365c0d62842e1/docs/HOST_TEXT_LAYOUT.md),223pinned to commit `9e03b1c0f365a15f51e68649311365c0d62842e1`. When the hook is224absent, the upstream layout is retained. The hook covers literal text groups,225including proof text passing through explicit font wrappers; it does not match226source strings or font names to fix individual formulas.227228The root Cargo patch pins all six RaTeX dependencies to that same Git revision229so workspace path dependencies share the parser/AST/font types. `Cargo.lock`230records the source; builds do not follow the fork's moving `main` branch.231The original corpus fixtures remain pinned to upstream v0.1.14, independently232of the implementation source. The fork keeps that version number, adds its233own API/depth regressions, and needs no RaTeX or LayMesh release for this work.234Future crate publication must retain the host-text API in the published RaTeX235dependency; publishing LayMesh core against unpatched registry 0.1.14 would236lose this integration.237238Validation includes 576 multilingual/domain combinations (24 cases × four239math fonts × inline/display × three sizes), actual font-advance/space metrics,240script-scale and shared-baseline checks, real bold/italic selection, ligatures,241combining marks, Arabic joining, explicit-list missing glyphs, disabled fallback,242LCSS-relative paths and ordinary-text font embedding. SVG/PDF/PNG/PPTX checks243cover Chinese, scripts, chemical annotations, proof labels, Arabic and Indic.244245```sh246cargo test -p laymesh-core --test formula_text247cargo test -p laymesh-render --test opentype_math248# Browse enabled text cases; append &text=0 to compare strict coverage.249# http://100.64.0.6:8768/?suite=text&baselines=1250```