Author SHA1 Message Date
gloamxun 51ea218e17 Record verified suffix previews and dependency-merge measurements 2026-12-02 06:23:37 +08:00
gloamxun f684872941 Stage verified suffix previews before new state hashing 2026-12-02 06:14:40 +08:00
gloamxun 5927196149 Record exact staged preview and measured Edge first-paint results 2026-12-02 06:08:33 +08:00
gloamxun c185483c46 Prime the observed generated version in the staged preview regression 2026-12-02 06:06:22 +08:00
gloamxun 58b0f16998 Let resumed SVG drafts precede a new final-state fingerprint 2026-12-02 05:58:32 +08:00
gloamxun 1a2379a6c2 Bound project index scans to the requested directory subtree 2026-12-02 05:58:31 +08:00
gloamxun 0f1b0f5978 Share proved macro prefixes during settled usage accounting 2026-12-02 05:58:31 +08:00
gloamxun 01a962ad99 Record exact line-end reuse and Edge first-paint comparisons 2026-12-02 05:47:29 +08:00
gloamxun 8ed0b70d5e Reuse verified command hash prefixes across rebuilt key orders 2026-12-02 05:37:34 +08:00
gloamxun 8f4ad600ef Promote edit-only entry checkpoints to proven line ends 2026-12-02 05:37:34 +08:00
gloamxun e05ad41a66 Record guarded child fallback and repeated Edge first-paint checks 2026-12-02 05:32:34 +08:00
gloamxun e659dcc86d Revert "Replay verified unchanged command blocks when hashing state"
This reverts commit 89e773b9f8.
2026-12-02 05:22:14 +08:00
gloamxun d1e9f61559 Retain an authenticated entry checkpoint before a child size read 2026-12-02 05:14:12 +08:00
gloamxun 89e773b9f8 Replay verified unchanged command blocks when hashing state 2026-12-02 05:13:31 +08:00
gloamxun 106268eb3c Record nested-prefix reuse and actual A4 first-paint evidence 2026-12-02 05:03:41 +08:00
gloamxun c331205c8c Retain validated child checkpoints for a prior observed size 2026-12-02 04:59:17 +08:00
gloamxun 128f0681f6 Resolve ordinary leaves under verified project parents directly 2026-12-02 04:59:17 +08:00
gloamxun 7164b1915a Avoid redundant expansion stack and closed-child accounting work 2026-12-02 04:59:17 +08:00
gloamxun 8903ae6c7a Record A4 final-state reuse, SVG equivalence and visible timings 2026-12-02 04:43:38 +08:00
gloamxun 841198615a Reuse exact final fingerprints of distinct published states 2026-12-02 04:41:41 +08:00
gloamxun af8f38bb78 Reuse logical namespace keys during native file checks 2026-12-02 04:41:41 +08:00
gloamxun 4586d961e9 Share exact repeated native glyph outlines in SVG previews 2026-12-02 04:41:41 +08:00
gloamxun 9f556d6a5f Measure native editor worker CPU at preview phase boundaries 2026-12-02 04:25:44 +08:00
gloamxun 10e497e6e0 Record direct SVG delivery and A4 visible latency evidence 2026-12-02 04:22:41 +08:00
gloamxun a72768bdb3 Deliver direct SVG drafts before native PDF export 2026-12-02 04:19:06 +08:00
gloamxun 37a42c82c8 Copy native command bindings through smaller persistent shards 2026-12-02 04:19:06 +08:00
gloamxun a7c2a571c1 Record exact fingerprint savings and native editor transport comparison 2026-12-02 04:02:49 +08:00
gloamxun 6adadd7237 Revert "Decode binary native preview replies without SVG text conversion"
This reverts commit 4df8983ff5.
2026-12-02 04:01:42 +08:00
gloamxun 4df8983ff5 Decode binary native preview replies without SVG text conversion 2026-12-02 03:58:07 +08:00
gloamxun 3c09d6486d Resume exact state fingerprints from ordered command checkpoints 2026-12-02 03:55:50 +08:00
gloamxun dc86f941b6 Record protected-path preparation and real browser retest 2026-12-02 03:40:42 +08:00
gloamxun b7e1c9078d Check overlapping generated path ownership once during preparation 2026-12-02 03:33:35 +08:00
gloamxun 143775b427 Reuse bound command keys and keep identical shared bindings 2026-12-02 03:33:33 +08:00
gloamxun ac93967cb2 Record accounting CPU reductions and browser latency tails 2026-12-02 03:22:37 +08:00
gloamxun d74933348d Share common macro accounting and reduce command checkpoint copies 2026-12-02 03:14:10 +08:00
gloamxun f558bf43ea Record native preview channel correctness and editor paint timing 2026-12-02 02:59:40 +08:00
gloamxun 44e5774b3a Deliver idle native editor previews over a persistent socket 2026-12-02 02:55:20 +08:00
gloamxun 3504a43bde Compare command shard entries directly when their order matches 2026-12-02 02:55:20 +08:00
gloamxun f1b95bd749 Record real A4 browser comparison of persistent preview delivery 2026-12-02 02:43:39 +08:00
gloamxun 65bf302f5f Maintain command source bounds across checkpoint revisions 2026-12-02 02:38:43 +08:00
gloamxun c8f7a0cbe6 Expose optional checkpoint clone and suffix proof timings 2026-12-02 02:38:43 +08:00
gloamxun 67396827a9 Record project Web paint timing and exact Opt3 accounting comparison 2026-12-02 02:20:39 +08:00
gloamxun ccb278fceb Count shared command shards once during suffix verification 2026-12-02 02:11:10 +08:00
gloamxun 7981493caf Record closed-child release latency and loopback controls 2026-12-02 02:05:31 +08:00
gloamxun e4d6e049f8 Reuse settled suffixes after verified closed child edits 2026-12-02 01:53:20 +08:00
gloamxun 55c497dccd Record default-release A4 presentation latency 2026-12-02 01:47:52 +08:00
gloamxun ed105bdd39 Reuse exact hash input for shared macro meanings 2026-12-02 01:35:49 +08:00
gloamxun c4003c8dad Reduce allocation and traversal in settled suffix checks 2026-12-02 01:23:14 +08:00
gloamxun 1ff049737f Prove suffix reuse across unequal retained histories 2026-12-02 01:06:03 +08:00
gloamxun f78aff25c5 Preserve read evidence and box accounting in settled suffix reuse 2026-12-02 00:47:50 +08:00
gloamxun 473b3beace Dispatch isolated editor edits promptly and measure browser paints 2026-12-02 00:23:48 +08:00
gloamxun bf42a88dff Reuse XeTeX suffixes across physical line edits 2026-12-02 00:22:21 +08:00
gloamxun 0b4aa49a71 Record PLOS ONE whole-line edit equivalence 2026-12-01 23:53:21 +08:00
gloamxun ac5f691a48 Reuse settled TeX suffixes after physical line edits 2026-12-01 23:49:39 +08:00
gloamxun 5b86a7ac7e Avoid extra copies while assembling relocated TeX suffixes 2026-12-01 23:32:01 +08:00
gloamxun 5b9eca1d60 Match pdfTeX link rectangles in repeated leaders 2026-12-01 23:30:43 +08:00
gloamxun aed7010cba Improve LaTeX input in the native web editor 2026-12-01 23:15:18 +08:00
gloamxun b081c951af Reduce and measure native suffix convergence work 2026-12-01 23:15:17 +08:00
gloamxun c008c52964 Reduce macro copying during native suffix convergence 2026-12-01 22:50:53 +08:00
gloamxun 57c05d9635 Reuse cached layouts for relocated native shipouts 2026-12-01 22:30:37 +08:00
gloamxun 41a459b4ca Relocate source provenance when native suffixes move 2026-12-01 22:17:10 +08:00
gloamxun 6acd82dbfa Reuse native checkpoints before source length changes 2026-12-01 21:42:04 +08:00
gloamxun 465a574124 Translate logical step counts when replaying native suffixes 2026-12-01 21:16:41 +08:00
gloamxun 9a6c162b46 Retain shared material across edited native page checkpoints 2026-12-01 20:54:19 +08:00
gloamxun c42a1a72aa Carry verified suffix checkpoints into later native edits 2026-12-01 20:33:01 +08:00
gloamxun 1cf985469c Keep bounded settled checkpoints beyond page eight 2026-12-01 20:01:17 +08:00
gloamxun a5dba52acb Retain verified suffix bases across consecutive page edits 2026-12-01 19:47:54 +08:00
gloamxun fe86163767 Load new math resources in the native Web editor 2026-11-29 14:01:40 +08:00
gloamxun 8b6dab8d52 Connect the native Beta to the project Web workspace 2026-11-29 13:36:48 +08:00
gloamxun 29193c03bc Save and reopen native Beta source snapshots 2026-11-29 13:30:18 +08:00
gloamxun 9841e88900 Provide a runnable local Beta and fix multi-page SVG previews 2026-11-29 13:19:00 +08:00
gloamxun fb557c09c6 Apply pdfTeX line box dimensions and restore output penalties 2026-11-29 12:49:56 +08:00
gloamxun 7f51f01bd4 Define a local Route-D beta before full acceptance 2026-11-29 12:40:30 +08:00
gloamxun 29aa6dc0a9 Record child checkpoint ownership and allocation measurements 2026-11-29 12:24:34 +08:00
gloamxun 6d0b2faceb Record deferred child replay accounting results 2026-11-29 12:07:46 +08:00
gloamxun 8bb47a5ead Record child continuation replay and measured validation cost 2026-11-29 11:37:43 +08:00
gloamxun 51db480b34 Advance replay checkpoints through completed entry lines 2026-11-29 11:10:17 +08:00
gloamxun d249ec7eba Reuse command lookup hashes and validate cached meanings by shard 2026-11-29 10:52:20 +08:00
gloamxun 330c4bde51 Match pdfTeX graphics-origin movement thresholds 2026-11-29 10:32:34 +08:00
gloamxun ecb0f60960 Use the rounded PDF graphics origin when starting text 2026-11-29 10:15:19 +08:00
gloamxun 893b46baae Add the original OUP journal project to the publisher matrix 2026-11-29 09:53:42 +08:00
gloamxun 050ff5bde2 Qualify three original REVTeX journal projects 2026-11-29 09:34:52 +08:00
gloamxun 4162c88826 Reuse native checkpoints for unchanged file-size observations 2026-11-29 09:24:06 +08:00
gloamxun 061e484001 Reject changed nested file sizes before checkpoint replay 2026-11-29 09:12:17 +08:00
gloamxun ffd84cd15b Share command bindings by partition across TeX checkpoints 2026-11-29 08:57:02 +08:00
gloamxun a8dfa14b7e Keep font kerns at the start of wrapped TeX lines 2026-11-29 08:34:22 +08:00
gloamxun 57ce7116ad Verify retained TeX accounting before reusing executed suffixes 2026-11-29 08:23:58 +08:00
gloamxun 0117449023 Reuse verified native suffixes after settled output routines 2026-11-29 07:51:37 +08:00
gloamxun f387b1db61 Replay verified completed native jobs on exact document undo 2026-11-29 07:19:47 +08:00
gloamxun d8af3518a7 Reuse native command meanings within a binding revision 2026-11-29 07:03:27 +08:00
gloamxun 9f4cc64c8f Match case-folded TeX dependencies in native resource lookup 2026-11-29 06:47:44 +08:00
gloamxun a1585339b9 Honor pdfTeX character program tags and qualify PLOS ONE 2026-11-29 06:26:35 +08:00
gloamxun 84ad682939 Resume validated native checkpoints inside included sources 2026-11-29 06:04:51 +08:00
gloamxun fb5cb5ada9 Store single native input tokens inline 2026-11-29 05:39:18 +08:00
gloamxun 9c93ff9750 Prioritize project blockers and measure remaining edit execution 2026-11-29 05:28:10 +08:00
gloamxun b37856eeb0 Write native XDV PDF versions and compact object streams 2026-11-29 05:21:01 +08:00
gloamxun 48d42052b8 Reuse resolved character categories within each native scan 2026-11-29 05:01:56 +08:00
gloamxun 4791c42403 Deduplicate native dependency reads on the execution path 2026-11-29 04:46:22 +08:00
gloamxun c23dabb449 Index native command meanings with deterministic state output 2026-11-29 04:37:03 +08:00
gloamxun 79bfee5ab1 Reuse equivalent native page layouts after execution 2026-11-29 04:24:15 +08:00
gloamxun f09bb04a32 Preserve physical Type 1C metadata and glyph widths 2026-11-29 04:14:22 +08:00
gloamxun d6e66cad12 Preserve sparse XDV TrueType glyph subsets 2026-11-29 04:03:12 +08:00
gloamxun 9efededf6d Carry XDV device advances through packed box scopes 2026-11-29 03:42:11 +08:00
gloamxun 9da75c82f5 Match XeTeX margin boundaries and Web2c glue rounding 2026-11-29 03:21:19 +08:00
gloamxun 52db77885d Read binary TeX inputs and render default ICC colors 2026-11-29 02:55:37 +08:00
gloamxun e9893a5c1b Ship named PDF color spaces and patterns from native color stacks 2026-11-29 02:35:22 +08:00
gloamxun 745c33fd44 Preserve conditional math glue through native layout 2026-11-29 02:16:50 +08:00
gloamxun 91bb864d8c Support native e-TeX middle delimiters and math segments 2026-11-29 02:05:21 +08:00
gloamxun e3be6dcd09 Reuse native checkpoints for unread stream changes 2026-11-29 01:54:35 +08:00
gloamxun 6a47d450f3 Resume native edits from verified final-line shipouts 2026-11-29 01:41:58 +08:00
gloamxun 93d3d38983 Carry resolved TeX command meanings through expansion 2026-11-29 01:28:05 +08:00
gloamxun c6b5c9ed56 Batch draft transcripts and reuse verified source versions 2026-11-29 01:11:42 +08:00
gloamxun 373204a8d8 Share native checkpoint command bindings and output probes 2026-11-29 01:00:10 +08:00
gloamxun 8aa079ec25 Match XDV PDF text origin and baseline rounding 2026-11-29 00:41:15 +08:00
gloamxun 90f174283e Continue XeTeX text layout on missing legacy glyphs 2026-11-29 00:28:09 +08:00
gloamxun cb6525ffca Run native editor sessions with the XeTeX profile 2026-11-29 00:10:42 +08:00
gloamxun 74eb1e9fc4 Resolve named XeTeX colors in native PDF and preview 2026-11-28 23:45:56 +08:00
gloamxun d6ab5a025f Share scanned source storage across native publications 2026-11-28 23:25:29 +08:00
gloamxun c09d545da6 Share native format and checkpoint source bytes 2026-11-28 23:16:20 +08:00
gloamxun 11c8ad1eaa Reuse verified Type 1 glyph and PDF subset output across edits 2026-11-28 23:03:13 +08:00
gloamxun 6939ff71ff Reuse unchanged shipout drawing lists after checkpoint resume 2026-11-28 22:50:16 +08:00
gloamxun e7ab132520 Render legacy XeLaTeX composite Type 1 fonts 2026-11-28 22:36:13 +08:00
gloamxun ff52a9f66b Render vertical and CFF legacy XeLaTeX composite fonts 2026-11-28 22:17:46 +08:00
gloamxun bbeeca0317 Render legacy XeLaTeX composite TrueType fonts 2026-11-28 21:59:30 +08:00
gloamxun 7d460e0fa1 Apply XeLaTeX CMaps to document text and embedded fonts 2026-11-28 21:40:17 +08:00
gloamxun af6466cd98 Bind shipped XeLaTeX font maps to native font resources 2026-11-28 21:22:51 +08:00
gloamxun dcc6a3984c Write XeLaTeX document name trees and attachments 2026-11-28 20:54:56 +08:00
gloamxun d627614af8 Measure XeLaTeX graphics links from device placement 2026-11-28 20:38:11 +08:00
gloamxun d875b69280 Import named PDF pages and images in the XeLaTeX device 2026-11-28 20:13:51 +08:00
gloamxun 5ad5c40002 Fit and clip captured XeLaTeX forms in their device coordinates 2026-11-28 19:47:20 +08:00
gloamxun c0e2346b05 Capture and reuse XeLaTeX PDF form contents 2026-11-28 19:29:07 +08:00
gloamxun 009fde04f7 Render XeLaTeX shared page resources and scoped graphics 2026-11-28 18:58:49 +08:00
gloamxun e20acc3eb9 Honor XeLaTeX page dictionaries and named rectangle coordinates 2026-11-28 18:36:52 +08:00
gloamxun e14361fec6 Write XeLaTeX named PDF objects and streams in native shipout 2026-11-28 18:22:15 +08:00
gloamxun c02f678bf7 Record A4 command binding sharing experiment 2026-11-28 17:52:21 +08:00
gloamxun d9143ddbd1 Reuse verified default font maps and streamline capacity scans 2026-11-28 17:16:57 +08:00
gloamxun 7707cd9b09 Expose active insertion height to pdfTeX macros 2026-11-28 16:39:02 +08:00
gloamxun 2fa11fb971 Expand native PDF image bounding-box queries 2026-11-28 16:20:17 +08:00
gloamxun 4fb0f2c89b Build native PDF article threads and bead rings 2026-11-28 16:03:37 +08:00
gloamxun de4bd1fa76 Ship native PDF annotations with reserved object numbers 2026-11-28 15:39:27 +08:00
gloamxun 975dbc8060 Recalculate native running links from the current PDF geometry 2026-11-28 15:17:40 +08:00
gloamxun cb8ed90df2 Keep native PDF navigation transforms across page output 2026-11-28 15:03:18 +08:00
gloamxun 0e71c15b01 Discard duplicate destinations during native PDF execution 2026-11-28 14:45:52 +08:00
gloamxun ba548ef05d Invoke frozen original primitives in native TeX 2026-11-28 14:19:26 +08:00
gloamxun 2007ac5627 Inspect original primitives and unexpanded tokens 2026-11-28 14:01:12 +08:00
gloamxun c094d9a81d Apply e-TeX line penalty arrays to native pagination 2026-11-28 13:44:30 +08:00
gloamxun 09cd19594c Retry earlier checkpoints after host replay changes 2026-11-28 13:17:46 +08:00
gloamxun d4e78bc29a Select named XeTeX faces by optical size 2026-11-28 13:01:52 +08:00
gloamxun 115e1f0fe0 Use OpenType design sizes in native XeTeX 2026-11-28 12:43:18 +08:00
gloamxun b472f66d04 Persist language-specific e-TeX hyphenation codes 2026-11-28 12:14:12 +08:00
gloamxun 11fd66713b Fit native paragraph endings using preceding line glue 2026-11-28 11:50:07 +08:00
gloamxun e72104eab3 Share size-independent XDV Type 1 font dictionaries 2026-11-28 11:19:57 +08:00
gloamxun 01c6f1d4bd Embed hinted Type 1C subsets for XeTeX PDF output 2026-11-28 11:07:18 +08:00
gloamxun 4ae4275cf3 Share XeTeX PDF font resources across compatible instances 2026-11-28 10:39:52 +08:00
gloamxun a864c6c5ca Merge native paragraph break candidates at the TeX line boundary 2026-11-28 10:21:53 +08:00
gloamxun 509f229a52 Apply Web2C TCX tables to native byte streams 2026-11-28 09:55:09 +08:00
gloamxun 3bb2330676 Record native LaTeX marks and MakeIndex workflow evidence 2026-11-28 09:22:32 +08:00
gloamxun d9edc6c6e7 Export native TeX shipouts as binary DVI 2026-11-28 09:05:18 +08:00
gloamxun 34325317d2 Honor e-TeX split shrink masks on native vertical lists 2026-11-28 08:46:51 +08:00
gloamxun 69efe0b895 Recognize space aliases when scanning TeX quantities 2026-11-28 08:20:52 +08:00
gloamxun da48cf9cad Share packed native lists across copied boxes and shipouts 2026-11-28 08:01:14 +08:00
gloamxun ca3730338e Share packed box diagnostics across native execution 2026-11-28 07:43:44 +08:00
gloamxun 526ec9b3b0 Scope XDV PDF content at the driver page origin 2026-11-28 07:25:57 +08:00
gloamxun ab6b1093ec Scan macro parameters using the current command meaning 2026-11-28 07:07:04 +08:00
gloamxun 2846f7f1e7 Resolve named XeTeX fonts from configured directories 2026-11-28 06:53:16 +08:00
gloamxun aae23d837e Preserve the XDV text line when switching OpenType fonts 2026-11-28 06:36:03 +08:00
gloamxun b22e127e93 Use physical Type 1 glyph widths in XeTeX PDF output 2026-11-28 06:23:12 +08:00
gloamxun 885911485e Handle unclaimed XeTeX specials at shipout 2026-11-28 06:04:09 +08:00
gloamxun e2af618e65 Support XeTeX OpenType vertical shaping and PDF writing mode 2026-11-28 05:24:33 +08:00
gloamxun 23ec506fa3 Preserve source CIDs in native XeTeX CFF export 2026-11-28 04:56:24 +08:00
gloamxun 82e54894c4 Resolve imported PDF CFF device fonts from real OpenType faces 2026-11-28 04:35:52 +08:00
gloamxun 84d6f3ae51 Render imported PDF TrueType device fonts from exact SFNT faces 2026-11-28 04:21:30 +08:00
gloamxun b640b26eff Resolve imported PDF Type 1 device fonts in native previews 2026-11-28 04:08:05 +08:00
gloamxun c0970bdbf6 Support unembedded pdfTeX Type 1 device fonts in export and preview 2026-11-28 03:44:29 +08:00
gloamxun 60d67bbb7b Read mapped Type 1 fonts from PFA programs 2026-11-28 03:19:37 +08:00
gloamxun 868814288c Resolve pdfTeX SFD subfonts against actual TrueType cmaps 2026-11-28 03:04:48 +08:00
gloamxun fd5ab59f42 Render and embed OpenType CFF fonts selected by pdfTeX maps 2026-11-28 02:46:19 +08:00
gloamxun 46ef76f890 Render and embed TrueType fonts selected by pdfTeX maps 2026-11-28 02:30:30 +08:00
gloamxun aa780a800b Reload letterspaced font metrics independently of generated packets 2026-11-28 02:08:44 +08:00
gloamxun 65204a7dae Rebind native format TFM resources after project relocation 2026-11-28 01:46:37 +08:00
gloamxun 1ad9c4db82 Bind native format inputs after moving a project tree 2026-11-28 01:29:28 +08:00
gloamxun c2e1e64a60 Retain XeTeX image lookup paths in native formats 2026-11-28 01:06:12 +08:00
gloamxun 6a118d3b60 Reuse PDF preview pages across object renumbering 2026-11-28 00:46:52 +08:00
gloamxun c1c3c25b3f Allocate mapped Type 1 import objects in PDF write order 2026-11-28 00:30:57 +08:00
gloamxun 861c9dbfc9 Allocate indirect PDF import objects during native writes 2026-11-28 00:06:51 +08:00
gloamxun 5a2df6781a Record ACM and Elsevier migration results and PDF import witness 2026-11-27 23:42:20 +08:00
gloamxun 0f10163b5b Include unboxed inline math in pdfTeX font expansion 2026-11-27 23:24:10 +08:00
gloamxun 8cd0263b97 Record current NeurIPS and ACM publisher comparisons 2026-11-27 23:00:59 +08:00
gloamxun f14669ae39 Honor PDF draft mode in native execution and publication 2026-11-27 22:48:48 +08:00
gloamxun af19a26c23 Order native PDF link continuations with shipout effects 2026-11-27 22:34:01 +08:00
gloamxun e95d1264da Register native PDF navigation and raw objects in write order 2026-11-27 22:19:15 +08:00
gloamxun 70ebacb056 Allocate compressed PDF object streams during native output 2026-11-27 22:02:52 +08:00
gloamxun d87464fde3 Reserve PDF image objects before expanding options 2026-11-27 21:40:49 +08:00
gloamxun 342bedf9b4 Allocate native PNG transparency and palette objects 2026-11-27 21:30:31 +08:00
gloamxun 51451813dc Allocate and share native PDF font objects 2026-11-27 16:15:18 +08:00
gloamxun d12c4b034b Share pdfTeX image and page object numbers 2026-11-27 15:54:24 +08:00
gloamxun 57a7097857 Restore PDF Forms from native formats 2026-11-27 15:31:24 +08:00
gloamxun c2d3312e5a Write native pdfTeX Form XObjects 2026-11-27 15:06:44 +08:00
gloamxun 7ff988031f Handle legacy XeTeX paper and landscape specials 2026-11-27 14:47:39 +08:00
gloamxun d944552188 Honor XeTeX page setup during native shipout 2026-11-27 14:38:19 +08:00
gloamxun 9da2ee41cd Restore XeTeX picture boxes at native shipout 2026-11-27 13:41:27 +08:00
gloamxun c2f18f50dc Restore registered pdfTeX images from native formats 2026-11-27 13:32:22 +08:00
gloamxun 1307bbcf0c Sync the changed ledger alongside native draft artifacts 2026-11-26 22:05:08 +08:00
gloamxun 140bb19849 Validate PDF page dependencies before reusing SVG previews 2026-11-26 18:36:10 +08:00
gloamxun 520e8eede2 Bind pdfTeX image color spaces to written PDF objects 2026-11-26 18:16:31 +08:00
gloamxun e10e0cce53 Honor pdfTeX page box selection and inherited PDF bounds 2026-11-26 17:56:57 +08:00
gloamxun 58012d9397 Resolve named PDF image destinations through the page tree 2026-11-26 17:41:30 +08:00
gloamxun 4c532f9396 Apply pdfTeX version policy at PDF image declaration 2026-11-26 17:19:56 +08:00
gloamxun 1fe0ac9dd5 Write per-page pdfTeX ProcSet from shipped resources 2026-11-26 17:03:52 +08:00
gloamxun de481fd762 Honor final pdfTeX font charset and document info omission 2026-11-26 16:48:27 +08:00
gloamxun 38c567623a Share physical Type 1 fonts across PDF page resources 2026-11-26 16:28:26 +08:00
gloamxun 5edd4ae4ec Write physical Type 1 subsets for imported PDF fonts 2026-11-26 16:03:43 +08:00
gloamxun a90d53c992 Remap Type1C fonts in imported pdfTeX pages 2026-11-26 15:39:14 +08:00
gloamxun f88a16d101 Preserve pdfTeX text positioning across direct color changes 2026-11-26 15:19:17 +08:00
gloamxun 0f6aa1f33d Resolve mapped Type 1 fonts for included pdfTeX pages 2026-11-26 14:59:15 +08:00
gloamxun 02d4c3116a Use live font choices for pdfTeX packed kerns 2026-11-26 14:33:49 +08:00
gloamxun 9e13cca481 Round pdfTeX font expansion before quantizing the font step 2026-11-26 14:18:44 +08:00
gloamxun 9ae7c6a6df Track pdfTeX expanded text with its active PDF matrix 2026-11-26 14:07:54 +08:00
gloamxun bd840df538 Match XDV PDF text cursor and Type 1 descriptor metrics 2026-11-26 13:49:41 +08:00
gloamxun eb0afccc03 Shape native XeTeX Graphite fonts with actual feature settings 2026-11-26 13:27:16 +08:00
gloamxun 76df2d6832 Normalize native XeTeX physical input before tokenization 2026-11-26 13:02:38 +08:00
gloamxun 048478c346 Execute ICU locale line breaks in native XeTeX paragraphs 2026-11-26 12:46:30 +08:00
gloamxun 4e16531a62 Read XeTeX font character ranges from active charmaps 2026-11-26 12:28:31 +08:00
gloamxun fc6d704edf Query actual XeTeX glyph bounds and names in native jobs 2026-11-26 12:11:40 +08:00
gloamxun b88283f493 Execute explicit XeTeX glyph nodes across native layout and export 2026-11-26 11:54:39 +08:00
gloamxun a0922d0105 Support scoped XeTeX OpenType colors in PDF and SVG 2026-11-26 11:27:13 +08:00
gloamxun 5a4271364a Implement XeTeX OpenType embolden across PDF and SVG 2026-11-26 11:06:36 +08:00
gloamxun 45ea5d4297 Implement XeTeX OpenType slant and transformed PDF text positioning 2026-11-26 10:43:04 +08:00
gloamxun 330ecdd03c Implement XeTeX OpenType horizontal scaling across layout and preview 2026-11-26 10:16:20 +08:00
gloamxun cc0246016d Implement XeTeX OpenType letterspacing and contextual line widths 2026-11-26 09:59:27 +08:00
gloamxun 4a77540e46 Implement XeTeX contextual interword spacing and shipout shaping 2026-11-26 09:23:45 +08:00
gloamxun 7e5428ec35 Implement XeTeX native word ActualText across shaping and shipout 2026-11-25 23:38:47 +08:00
gloamxun 97319d751b Recover XeTeX PDF Unicode from actual OpenType glyph mappings 2026-11-25 23:16:13 +08:00
gloamxun c52ad71bad Convert XeTeX OpenType script and language tags before shaping 2026-11-25 22:48:51 +08:00
gloamxun 3e9a639f1d Rejoin XeTeX OpenType word fragments while packing horizontal boxes 2026-11-25 22:29:53 +08:00
gloamxun fa27e0985f Write XeTeX PDF font descriptors from OS/2 and CFF data 2026-11-25 22:15:06 +08:00
gloamxun 2b82172bfb Select XeTeX OpenType vertical metrics from the font tables 2026-11-25 21:52:56 +08:00
gloamxun c97e0e7279 Hyphenate native XeTeX OpenType words during line breaking 2026-11-25 21:37:05 +08:00
gloamxun 20986b2fd5 Ship XDV annotations from measured page ranges 2026-11-25 21:12:44 +08:00
gloamxun 515dbe6181 Ship XDV document views and PDF outline navigation 2026-11-25 20:32:05 +08:00
gloamxun 8be7867b37 Apply XDV color state and page backgrounds at shipout 2026-11-25 20:09:15 +08:00
gloamxun cc147e93d8 Resolve XDV named destinations at PDF shipout 2026-11-25 19:47:17 +08:00
gloamxun dd695a8945 Merge XDV document information in shipout order 2026-11-25 19:28:12 +08:00
gloamxun 6826efbeb1 Use shaped glyph edges for XeTeX protrusion and line breaking 2026-11-25 19:09:56 +08:00
gloamxun 5df90f113c Execute XeTeX character classes and inter-character token lists 2026-11-21 17:31:30 +08:00
gloamxun d11ac0cba1 Decode XeTeX input files and streams with original byte spans 2026-11-21 17:10:46 +08:00
gloamxun 22e3ba993d Execute and render TeX--XeT direction spans in native layouts 2026-11-21 16:46:17 +08:00
gloamxun a93d1bb902 Discard paragraph fill after a break that consumes the tail 2026-11-21 16:17:22 +08:00
gloamxun 767c8ffced Resolve named XeTeX fonts through captured resource catalogues 2026-11-21 15:54:06 +08:00
gloamxun a31de14eb2 Match XeTeX math script kerning and fraction font selection 2026-11-21 15:33:05 +08:00
gloamxun 821631778e Render XeTeX OpenType math accents and stretch constructions 2026-11-21 15:14:48 +08:00
gloamxun 01b3931ae0 Execute XeTeX Unicode delimiter codes and primitives 2026-11-21 14:48:38 +08:00
gloamxun dba73f1f47 Support deep TeX numeric scans with bounded stack growth 2026-11-21 14:34:55 +08:00
gloamxun 7070cc6b82 Resolve XeTeX font probes and expose real OpenType math parameters 2026-11-21 14:23:48 +08:00
gloamxun 01ef302fb0 Scan extended XeTeX superscript character notation 2026-11-21 14:04:00 +08:00
gloamxun 2bd6e19519 Render native XeTeX PNG, JPEG and BMP graphics 2026-11-21 13:58:26 +08:00
gloamxun 794c2f9b2c Include PDF graphics in the native XeTeX device 2026-11-21 13:34:55 +08:00
gloamxun facecbf790 Measure native XeTeX glyphs and break after mapped dashes 2026-11-21 12:58:25 +08:00
gloamxun c548ca8e9f Execute TECkit font mappings in native XeLaTeX jobs 2026-11-21 12:39:29 +08:00
gloamxun 752af43f32 Select a native XeTeX compatibility profile and wide spacing codes 2026-11-21 12:17:53 +08:00
gloamxun 651fab42f1 Expand native Unicode character primitives and definitions 2026-11-21 11:58:23 +08:00
gloamxun d17680fcd8 Execute Unicode math codes and measured OpenType math characters 2026-11-21 11:47:56 +08:00
gloamxun ce8a780031 Execute positioned TeX specials through native PDF devices 2026-11-21 11:24:46 +08:00
gloamxun 05e633bb14 Record native XeLaTeX format bootstrap and article blockers 2026-11-21 11:04:39 +08:00
gloamxun b681f9791a Reduce repeated macro tracing and input position work 2026-11-21 10:54:11 +08:00
gloamxun 70822cbd94 Shape and render explicit OpenType fonts in native Unicode jobs 2026-11-21 10:35:03 +08:00
gloamxun 3caf1eced2 Render Type1 map slant and extension in PDF and SVG 2026-11-21 10:04:48 +08:00
gloamxun 28dfba5a5e Apply job-local PDF font maps at execution and shipout 2026-11-21 09:53:31 +08:00
gloamxun 9527d3bbec Reject automatic expansion of bitmap fonts at PDF shipout 2026-11-21 09:38:18 +08:00
gloamxun 45b79fc5a5 Apply inherited virtual font expansion limits 2026-11-21 09:27:10 +08:00
gloamxun 614f09aa9b Register virtual fonts in native PDF shipout order 2026-11-21 09:18:03 +08:00
gloamxun b008c0693a Separate format font metrics from live expansion links 2026-11-21 08:43:02 +08:00
gloamxun 9b80a782cf Allocate native automatic font expansion instances 2026-11-21 08:27:32 +08:00
gloamxun 2d036b807e Record marginal expansion, cache reuse and TFM recovery 2026-11-21 08:08:12 +08:00
gloamxun 1e4c113b27 Measure external font expansion at paragraph break margins 2026-11-21 08:08:11 +08:00
gloamxun 91b3e6a8fe Record external expansion, font edits and remaining edge search 2026-11-21 07:41:46 +08:00
gloamxun 12d9eb6a54 Use external expanded font metrics in native paragraph layout 2026-11-21 07:41:45 +08:00
gloamxun 4ad66c120d Record native PDF space font and publisher verification 2026-11-21 07:17:35 +08:00
gloamxun 584b708487 Allocate dedicated PDF spaces in the native font catalog at shipout 2026-11-21 07:11:48 +08:00
gloamxun 4bd7f1e08e Record original ACM structure destination convergence 2026-11-21 06:50:52 +08:00
gloamxun 3ff339341b Put native PDF warnings on separate diagnostic lines 2026-11-21 06:45:35 +08:00
gloamxun 75d3667397 Bind native format jobs to their validated pdfTeX revision 2026-11-21 06:43:26 +08:00
gloamxun d02777a1fc Report active native math alignment and output lists 2026-11-21 06:26:49 +08:00
gloamxun 3ed2c2cd54 Print DVI dictionary warnings on their own TeX lines 2026-11-21 06:03:17 +08:00
gloamxun 1822ab2d32 Apply native automatic kerns and protrusion at real line edges 2026-11-21 06:00:55 +08:00
gloamxun f66a5a7e20 Implement native letterspaced fonts and virtual glyph placement 2026-11-21 05:48:44 +08:00
gloamxun 6675ab639a Redirect native TeX diagnostics to real output streams 2026-11-21 05:38:05 +08:00
gloamxun 6ebcb75794 Record original ACM PDF and bibliography convergence 2026-11-21 05:19:43 +08:00
gloamxun 003d5d8726 Resolve FitR destinations using shipped box geometry 2026-11-21 05:18:07 +08:00
gloamxun 22154b53a6 Resolve native PDF structure destinations and local actions 2026-11-21 05:04:54 +08:00
gloamxun 58bcfca7b7 Record original ACM local structure action boundary 2026-11-21 04:50:31 +08:00
gloamxun e113033b8a Expand native PDF checksums over resolved input bytes 2026-11-21 04:41:46 +08:00
gloamxun 6d2a4921cf Record original ACM checksum boundary after saved positions 2026-11-21 04:35:38 +08:00
gloamxun 413939911f Save the TeX cursor in native shipout order 2026-11-21 04:27:06 +08:00
gloamxun 555a029505 Import PNG images in the native PDF device 2026-11-21 04:13:18 +08:00
gloamxun 297431a547 Retain signed glue in native display lists 2026-11-21 03:56:17 +08:00
gloamxun c6701204ec Record original ACM display skip boundary 2026-11-21 03:47:40 +08:00
gloamxun 278b1f35e2 Execute native PDF device extensions in math lists 2026-11-21 03:40:31 +08:00
gloamxun d1ddf4bfeb Apply native PDF page dictionaries and viewport projection 2026-11-21 03:31:00 +08:00
gloamxun a6ba70aa46 Record original ACM page dictionary boundary 2026-11-21 03:18:36 +08:00
gloamxun 514a2d3344 Write PDF interword spaces with actual device fonts 2026-11-21 03:09:10 +08:00
gloamxun b93d5f55da Record original ACM first-page space diagnostic 2026-11-21 02:51:41 +08:00
gloamxun b647bd8dcd Support native PDF font dictionaries and running link controls 2026-11-21 02:46:57 +08:00
gloamxun 60d7411dfe Bind native last-link numbers to shipped PDF annotations 2026-11-21 02:31:43 +08:00
gloamxun 7f74251c8a Track PDF literal transforms in native source maps 2026-11-21 02:23:12 +08:00
gloamxun d46d6d79a8 Expose stored left and right margin kerns from native boxes 2026-11-21 02:13:39 +08:00
gloamxun 432c1d2ba7 Emit native PDF literals at scan and shipout boundaries 2026-11-21 02:03:25 +08:00
gloamxun 13ab32247d Implement native paragraph token naming and execution contexts 2026-11-21 01:49:10 +08:00
gloamxun 862801ee5f Preserve alignment boundaries when matching hash-brace macros 2026-11-21 01:36:06 +08:00
gloamxun 307303d596 Resolve expandable PDF page references to shipped page objects 2026-11-21 01:25:00 +08:00
gloamxun 5c2ba9fad0 Implement pdfTeX random primitives with checkpointed state 2026-11-21 01:10:55 +08:00
gloamxun a958954308 Read file-backed PDF objects at their actual write boundary 2026-11-21 01:02:40 +08:00
gloamxun 4f4a4567ea Emit native PDF page resources and named transparency states 2026-11-21 00:53:46 +08:00
gloamxun 2bced813a2 Record original Elsevier double-column first output 2026-11-20 23:48:25 +08:00
gloamxun 6d54af5350 Expand deferred TeX input without recursive dispatch frames 2026-11-20 23:40:14 +08:00
gloamxun ebbc9e2c17 Implement native automatic font expansion for paragraphs 2026-11-20 23:29:37 +08:00
gloamxun 1dd745afcb Prioritize feature implementation before consolidated acceptance 2026-11-20 23:08:30 +08:00
gloamxun 4777d66fc8 Apply native font protrusion during line breaking and packing 2026-11-20 17:18:25 +08:00
gloamxun 361e8d070f Reuse decoded Type 1 fonts across native revisions 2026-11-20 16:55:48 +08:00
gloamxun 6e573dc1ce Run cancellable pdfTeX matching in native frontends 2026-11-20 16:43:48 +08:00
gloamxun 091458d329 Verify schema 28 format round trips and rejection gates 2026-11-20 16:21:19 +08:00
gloamxun 4eeb5686b8 Implement native text accents for unmodified LaTeX jobs 2026-11-20 16:15:30 +08:00
gloamxun ca60c66a17 Reuse the active edit line within the checkpoint budget 2026-11-20 16:08:36 +08:00
gloamxun 600160f624 Record edit-line latency and text accent evidence 2026-11-20 15:48:44 +08:00
gloamxun e4a265ca6c Reuse valid checkpoints across auxiliary file changes 2026-11-20 15:17:28 +08:00
gloamxun 3a3913a385 Verify earlier checkpoints on original CVPR edits 2026-11-20 14:29:50 +08:00
gloamxun 0a21eb27a7 Reuse session-verified source versions in native source maps 2026-11-20 14:18:42 +08:00
gloamxun 225736ce80 Measure the A4 edit-to-paint critical path 2026-11-20 14:04:20 +08:00
gloamxun 4575150f92 Record native source-map reuse and CVPR invalidation evidence 2026-11-20 13:23:44 +08:00
gloamxun 592d1ef2a3 Reuse byte-verified source versions after checkpoint resume 2026-11-20 13:02:50 +08:00
gloamxun 0ff8597ab4 Verify live edits on official IEEE and CVPR projects 2026-11-20 12:39:35 +08:00
gloamxun ae59cc1cc1 Record live source-version reuse across complete paired edits 2026-11-20 12:19:14 +08:00
gloamxun 1038fcf709 Record sharded binding timings and source hash call chains 2026-11-20 09:37:34 +08:00
gloamxun ae6ddb47d0 Record command binding checkpoint and live preview comparisons 2026-11-20 09:20:29 +08:00
gloamxun a1ed9498bc Verify file-revision checkpoints across browser and publisher corpus 2026-11-20 08:59:13 +08:00
gloamxun 1ba46a9f61 Record live file-edit and original A3 verification 2026-11-20 08:31:34 +08:00
gloamxun 287d4a7cf0 Validate live checkpoint reuse across atomic project file changes 2026-11-20 08:26:44 +08:00
gloamxun e77b15d8bd Record paired upstream and browser preview timings 2026-11-19 22:46:59 +08:00
gloamxun da277611e8 Record complete workspace validation for live file identity 2026-11-19 22:43:15 +08:00
gloamxun 45455c4cc0 Measure upstream preamble reuse on publisher templates 2026-11-19 22:41:07 +08:00
gloamxun 6438c3475d Record upstream reuse and editor cancellation experiments 2026-11-19 22:35:20 +08:00
gloamxun 50bd410574 Document live TeX priorities and verified publisher results 2026-11-19 22:20:28 +08:00
gloamxun 24ea6ef7ee Reuse fixed file identity within a live alias scan 2026-11-19 22:02:53 +08:00
gloamxun 1c02d8af25 Trace live alias checks and GNU regex cancellation 2026-11-19 21:52:39 +08:00
gloamxun 7e67494863 Verify buffered fingerprints across the workspace and publisher corpus 2026-11-19 21:38:06 +08:00
gloamxun 10a08c4597 Batch native state fingerprint writes for live editing 2026-11-19 21:15:54 +08:00
gloamxun 959dd4f24a Measure real A4 hyphenation fingerprint reuse 2026-11-19 20:59:32 +08:00
gloamxun 37ae9b5e9e Verify real A3 continuation at the edited line 2026-11-19 20:35:19 +08:00
gloamxun 2368db1d71 Verify input resolution across compiler and publisher jobs 2026-11-19 20:29:32 +08:00
gloamxun 11063c65dd Record pdfTeX margin behavior and capture checkpoint evidence 2026-11-19 20:15:49 +08:00
gloamxun ee22f25ee0 Resolve TeX inputs with the default suffix alternatives 2026-11-19 20:01:08 +08:00
gloamxun 901a50c36c Record A4 preview transport timing 2026-11-19 19:32:32 +08:00
gloamxun 48c980c871 Share TeX hyphenation patterns and reuse verified state fingerprints 2026-11-19 19:00:55 +08:00
gloamxun 3ffa452fd1 Use file identities for Unix alias checks 2026-11-19 18:43:34 +08:00
gloamxun 3faac740bd Test official ACM journals and proceedings 2026-11-19 18:25:37 +08:00
gloamxun ab50ca7dad Reuse project directory indexes within a revision 2026-11-19 18:14:31 +08:00
gloamxun 41af3d8d22 Cancel jobs while their private file sync drains 2026-11-19 18:01:50 +08:00
gloamxun f6c493e462 Edit multiple project buffers in the native preview 2026-11-19 17:39:01 +08:00
gloamxun b5e87a8706 Stop obsolete draft rendering between pages 2026-11-19 17:28:55 +08:00
gloamxun eda01fb689 Show native preview during durable file publication 2026-11-19 17:19:11 +08:00
gloamxun 75d156f0cf Retain recent checkpoints for alternating body edits 2026-11-19 17:02:26 +08:00
gloamxun d587405d2e Record mixed editing latency and retention regression 2026-11-19 16:44:45 +08:00
gloamxun 393fba42d8 Reuse closed events and line breaking after a checkpoint 2026-11-19 16:39:08 +08:00
gloamxun fc6786d9f4 Record current real-format preview equivalence 2026-11-19 16:29:09 +08:00
gloamxun 8d3a2f8f27 Record fresh CVPR and microtype template baselines 2026-11-19 16:19:29 +08:00
gloamxun 28668ea10f Refresh interactive TeX state across successive edits 2026-11-19 16:19:29 +08:00
gloamxun 38e4822370 Integrate native repeat boxes and PDF bookmarks 2026-11-19 16:06:28 +08:00
gloamxun 5163fc9854 Overlap durable sync for interactive document drafts 2026-11-19 16:01:20 +08:00
gloamxun 062a2b9f60 Prioritize edit-to-visible TeX compilation 2026-11-19 15:46:53 +08:00
gloamxun 366c381310 Align publisher job names and extend conference coverage 2026-11-19 15:36:12 +08:00
gloamxun 9ce878efd4 Match paragraph tokens in macro delimiters 2026-11-19 15:06:50 +08:00
gloamxun 5aa7dc7331 Stream native failure manifests during publication 2026-11-19 14:50:11 +08:00
gloamxun 72ed779749 Promote verified native PDF and box capacity support 2026-11-19 14:39:39 +08:00
gloamxun 3706afa483 Record text accent parity and pending publisher gates 2026-11-19 14:24:14 +08:00
gloamxun d2d9f3d37f Record schema27 publisher matrix and overlapping sync proof 2026-11-19 14:14:36 +08:00
gloamxun c79d44f99f Record optimized bookmark and publication differentials 2026-11-19 13:45:37 +08:00
gloamxun a83b6b8404 Record native bookmark and draft sync verification 2026-11-19 13:17:59 +08:00
gloamxun 026bb15d9b Coalesce native draft ledger writes
Preserve checked final ledger bytes with one private file and keep the published ledger when unchanged. Record the full workspace, browser, and original publisher differentials.
2026-11-19 12:57:14 +08:00
gloamxun 649a2f4d6f Record clean A3 and schema25 article differentials 2026-11-19 12:34:19 +08:00
gloamxun ba634496fe Record paired ledger and original publisher verification 2026-11-19 12:18:43 +08:00
gloamxun 67eba7b407 Record phased preview timings and leader compatibility evidence 2026-11-19 11:48:51 +08:00
gloamxun 43231a48c0 Reuse validated checkpoint executors during native preview 2026-11-19 11:16:40 +08:00
gloamxun 69de8a6599 Record publisher font and JPEG reference evidence 2026-11-19 10:46:25 +08:00
gloamxun 742afb7d9c Record optimized native editor browser baseline 2026-11-19 10:21:04 +08:00
gloamxun 06463399bb Enable automatic native checkpoints and browser preview 2026-11-19 10:05:41 +08:00
gloamxun bb1a166c4c Record browser evidence for native incremental preview 2026-11-19 09:51:07 +08:00
gloamxun 0abf700817 Resume native editor jobs through verified checkpoints 2026-11-19 09:35:33 +08:00
gloamxun 31364ae33e Record automatic checkpoint selection and publisher format audit 2026-11-19 09:22:35 +08:00
gloamxun 60aec30595 Record A3 checkpoint publication and PDF metadata verification 2026-11-19 09:03:45 +08:00
gloamxun f4b003bd27 Write native PDF catalogs and open actions 2026-11-19 08:54:04 +08:00
gloamxun a53d9c9bf9 Implement native PDF links and vertical discard lists 2026-11-18 23:39:45 +08:00
gloamxun b6567f67e2 Record revision-gated checkpoint publication verification 2026-11-18 23:23:58 +08:00
gloamxun d8e3b06426 Record publisher template compatibility progress 2026-11-18 22:59:58 +08:00
gloamxun 2741546ca8 Advance native LaTeX execution and preview 2026-11-18 22:17:21 +08:00
gloamxun 91f9d76b16 Audit the word-sequence residual 2026-10-29 00:54:29 +08:00
gloamxun e1ae10f2ce Document the math spacing paint gap 2026-10-29 00:51:04 +08:00
gloamxun bf4e758fba Document the math metric mismatch 2026-10-29 00:47:28 +08:00
gloamxun e34558efb8 Update the scoped acceptance metrics 2026-10-29 00:18:05 +08:00
gloamxun 96b40c1c2e Tighten large-operator lower limits 2026-10-29 00:15:15 +08:00
gloamxun a9f3cab8dc Measure the fraction rule mismatch 2026-10-29 00:07:21 +08:00
gloamxun 828b9716a1 Refresh the scoped acceptance snapshot 2026-10-29 00:06:38 +08:00
gloamxun a89277fe1a Record article float and fraction probes 2026-10-29 00:03:15 +08:00
gloamxun 7cd221e7a9 Put 3.3 Tables on page two for Times arXiv output 2026-10-28 23:58:49 +08:00
gloamxun 59308eb01a Record the page-2 float reservation 2026-10-28 23:49:06 +08:00
gloamxun eabebfa687 Compact display-to-heading gaps in Times math 2026-10-28 23:45:34 +08:00
gloamxun 13b85b542a Compact consecutive Times heading glue 2026-10-28 23:39:01 +08:00
gloamxun 16a795bca2 Measure the page-2 3.2 block drift 2026-10-28 23:31:18 +08:00
gloamxun 2c81e7cb44 Record the arXiv unit ordering diagnosis 2026-10-28 23:29:16 +08:00
gloamxun 9efd2b61be Document the page-2 fit shortfall 2026-10-28 23:27:10 +08:00
gloamxun 01b3f518cb Add bounded line expansion for Times body text 2026-10-28 23:19:16 +08:00
gloamxun 8fef7df187 Define the scoped route-D fidelity goal 2026-10-28 23:04:26 +08:00
gloamxun c6743e2f9e Record final warm-preview variance 2026-10-28 14:09:19 +08:00
gloamxun fe0784cdc6 Record the route-D acceptance snapshot 2026-10-28 14:07:41 +08:00
gloamxun d28e21e3d4 Use arxiv.sty display skips in Times math
arxiv.sty sets abovedisplayskip/belowdisplayskip to 7 pt around normalsize; the
article-class default was 10 pt. Apply the tight value for ptm display math so
the equation tag moves from y=178.49 to y=175.49 (TeX y=174.9). Add a unit test
for the skip tuple; workspace tests are now 1089.
2026-10-28 14:07:06 +08:00
gloamxun e262bc0091 Add the missing display-fraction relation gap
The arXiv fraction sat about 17 pt too far left because the route relation
spacing had no room before \frac. Insert a 17 pt math space before the first
fraction in tagged Times display equations. The formula text span moves from
x=144.7..540.9 to x=135.4..540.9; TeX is x=132.7..540.7. Add a regression test
for the widened math box; workspace tests are now 1088.
2026-10-28 14:02:58 +08:00
gloamxun d3175bcd1c Quantify the page-2 heading drift 2026-10-28 13:58:22 +08:00
gloamxun 4ae362e4dd Test Times table column metrics 2026-10-28 13:51:32 +08:00
gloamxun 049365d595 Use Times metrics for table column widths
Halign measured every cell with the CMR default even in Times documents, so the
sample table was wider than TeX and page 3 ink reached x=553. Give Halign an
optional paragraph face and refresh column widths in that face; route-D now
selects TimesRoman for ptm tabulars. Page 3 ink bbox moves to x=540, matching
the reference.
2026-10-28 13:51:00 +08:00
gloamxun 43f8c979cf Match natbib bibliography layout and citation order 2026-10-28 13:44:47 +08:00
gloamxun ba61faf142 Format BibTeX entries like unsrtnat
Rewrite author names as First Last (with Oxford-comma lists), use plain titles
and italic journal/booktitle with In, order the bibliography by first citation,
carry the 2014a/b suffix into the reference text, and fix page/publisher
punctuation. The valid TeX-oracle score rises from 0.8605 to 0.8958.

Add two formatter tests; the workspace now has 1086 tests.
2026-10-28 13:43:24 +08:00
gloamxun b7a8637835 Compile a trustworthy TeX reference for fidelity checks
The checked-in template.pdf is stale: its references.bib snapshot does not
match the checked-in .bib, so earlier scores used the wrong oracle. Add a
reproducible pdflatex/bibtex script that copies the fixture, drops the unused
cleveref package (cleveref/hyperref socket mismatch in this TeX Live), defines
languagename for lipsum, and produces a valid 3-page reference. Re-score route-D
against it: 1243 reference words, 1251 candidate words, ratio 0.8605.
2026-10-28 13:35:28 +08:00
gloamxun b8573a2e70 Record the rejected top-level math spacing trial 2026-10-28 13:31:21 +08:00
gloamxun f39733a283 Record the 50-round route-D fidelity report 2026-10-28 12:19:20 +08:00
gloamxun d4c16b69b4 Record the display-equation bbox residual 2026-10-28 12:14:17 +08:00
gloamxun 905b63d1ef Record that the six-line path is unreachable 2026-10-28 12:12:27 +08:00
gloamxun 1959b18f82 Assert ORCID badges in the SVG preview
The arXiv preview must contain exactly two PNG data URIs for the author badges
and no iD text marker. This covers the SVG half of the ORCID post-processing;
the PDF half is covered by the display-list unit test.

Test count stays 1084.
2026-10-28 09:20:33 +08:00
gloamxun c4392e72a3 Document the residual 2.1 line-break path 2026-10-28 09:18:56 +08:00
gloamxun 730b04bce5 Refresh the fidelity score after ORCID badges 2026-10-28 09:15:00 +08:00
gloamxun c742e21a81 Render ORCID markers as badge images
Replace the iD text marker after pagination with a generated 32x32 ORCID-green
badge containing a white iD glyph. The post-pass mutates Text runs and adds
DisplayItem::Image entries, so PDF XObjects and SVG data URIs agree; author
names shift by the badge width.

Test count is 1084.
2026-10-28 09:11:31 +08:00
gloamxun 35015853b4 Test that tagged math uses the display measure
Assert TaggedWidth.width equals the measure, protecting the right-margin
equation tag geometry while the formula body remains approximate.

Test count is 1083.
2026-10-28 09:03:37 +08:00
gloamxun af20ce8dc9 Record the mixed math font backend 2026-10-28 08:55:17 +08:00
gloamxun e41492b2a0 Keep CMMI/CMSY Type1 math in Times PDFs
The TrueType Times backend also sent math glyphs through Liberation fallbacks,
which changed their size and spacing. Allow the math face slots (6..10) to use
their Computer Modern Type1 programs even when the text backend is TrueType,
and add a PDF test asserting CMMI10 plus LiberationSerif in the same file.

Test count is 1082.
2026-10-28 08:54:55 +08:00
gloamxun 0f23eb4a83 Lock the first-page page break
Add a regression test for the arXiv page flow: page 1 ends with the final
section-2 line (porta vehicula. See Section 2.) and page 2 starts at
2.1 Headings. This protects the Times baselineskip/glue fix.

Test count is 1081.
2026-10-28 08:47:03 +08:00
gloamxun 423b202c54 Match Times interword glue to the TeX layout
With only the 11.5pt baselineskip, page 1 was fixed but the 2.1 paragraph
still took seven lines instead of six and pushed the equation to y=190. Use
Times glue of 2.5/1.5/0.83pt; page 1 stays aligned, 2.1 returns to six lines,
and the equation number moves to y=178 (TeX: 175).

Test count stays 1080.
2026-10-28 08:44:42 +08:00
gloamxun 764436fc71 Record the post-baselineskip fidelity score 2026-10-28 08:41:29 +08:00
gloamxun 53bf50b0e9 Use an 11.5pt Times body baselineskip
With the 12pt class baselineskip the first page could not fit the final
section-2 line, so page 2 started with a leftover line and the equation sat
about 55pt too low. An 11.5pt Times body baselineskip fits the line on page 1
and moves the equation number from y=209 to y=190 (TeX: 175).

Drop the earlier 2.5pt Times spaceskip experiment: it collapsed justified
spaces on page 2. Test count stays 1080.
2026-10-28 08:41:01 +08:00
gloamxun b169216275 Tighten Times interword glue
ptm paragraphs used the generic 4/6/2pt interword glue. Set the Times skip to
2.5/1.5/2.5pt, which lets the first page fit more of the final section-2 line
and moves the page-2 equation about 21pt closer to TeX.

Test count stays 1080.
2026-10-28 08:33:20 +08:00
gloamxun 676eb7f323 Keep sum superscripts above the operator
Large-operator limits used the ordinary-base superscript gap, which could
leave N just below the sum baseline. Use a negative gap for large operators
so both limits straddle the operator, and add a unit test asserting the
subscript is below and the superscript above the base within 12pt.

Test count is 1080.
2026-10-28 08:28:17 +08:00
gloamxun 02742d201f Keep large-operator limits close to the operator
Display limits under \sum used the operator glyph depth, which pushed i=1 far
below the fraction and made the denominator look detached. Use the normal
limit gap for big operators while preserving the depth-based placement that
the existing \mathop oracle validates for ordinary bases.

Test count stays 1079.
2026-10-28 08:17:57 +08:00
gloamxun 68ec9941dc Add an equation tag and script regression test
Cover the arXiv equation through the preview SVG: no literal underscore/caret
text items may remain, and the equation number must sit near the right margin.
This locks the script-attachment and TaggedWidth fixes.

Test count is 1079.
2026-10-28 08:03:59 +08:00
gloamxun 8f231d5752 Refresh the fidelity score after DOI support 2026-10-28 00:54:38 +08:00
gloamxun 1b0f4c8ab3 Append DOI fields to project bibliography entries
.format_bib_entry ignored the doi field, so the arXiv first reference lost its
doi:10.1109/... suffix. Append doi:<value> when present and extend the server
bib test fixture/assertions.

Test count stays 1078.
2026-10-28 00:54:05 +08:00
gloamxun eb2cb561bd Add a reproducible TeX fidelity benchmark
Add scripts/tex-fidelity.py: page count, normalized word-sequence similarity and
per-page ink bounds from a 72 dpi grayscale render, using only the stdlib and
Poppler. Document the current arXiv score (0.848 word ratio, 3 pages) and its
limits.

Test count stays 1078.
2026-10-28 00:50:37 +08:00
gloamxun d5de8b9fe6 Attach math scripts across ignored spaces
TeX ignores spaces in math mode, but parse_sequence looked for _ or ^ at the
raw next index. Source such as \alpha _{i} therefore rendered the underscore
as a literal symbol at full size. Skip math spaces after the base before
checking for scripts.

The arXiv equation now has real subscripts and superscripts instead of literal
underscores. Test count is 1078.
2026-10-28 00:48:51 +08:00
gloamxun 742986e4dd Correct fraction depth and subscript placement
The fraction box added bar clearance twice to its depth, leaving extra space
below the denominator. Use the painted extent instead. Scripts now include
script space after the base, and subscripts drop by the base depth plus 2pt
rather than sitting on the baseline when the base has no depth.

Test count stays 1077.
2026-10-28 00:43:25 +08:00
gloamxun 802526c352 Reserve full fraction extents in math layout
Fraction layout scaled numerator and denominator extents by 0.7 while painting
both at the full size, underestimating the box height and depth. Use the full
extents plus the bar clearance so the display equation no longer compresses its
fraction vertically.

Test count stays 1077.
2026-10-28 00:39:05 +08:00
gloamxun 764bc18850 Place display equation tags at the right margin
Tagged display math used the body width as its box, so the equation number sat
immediately after the formula. Add a TaggedWidth atom carrying the line
measure: the body is centred in the measure and the tag is painted at its right
edge.

The arXiv equation number now matches the TeX right-margin placement; the
formula body remains approximate. Test count stays 1077.
2026-10-28 00:32:56 +08:00
gloamxun 9181bf49fe Record lipsum preview latency 2026-10-28 00:27:04 +08:00
gloamxun 0562b13be8 Use the real lipsum package text
The filler array was a short Lorem ipsum paraphrase, so \lipsum[1] produced
about half the lines of the lipsum package and every later page break was
wrong. Replace the ten paragraphs with the actual lipsum.ltd.tex text.

The arXiv sample now has the same abstract/introduction flow as TeX and both
figure and table land on page 3 above 3.3/3.4; test count stays 1077.
2026-10-28 00:26:30 +08:00
gloamxun 3780aef88c Keep an iD marker for ORCID author graphics
Author metadata contains an ORCID PDF icon inside href; the author block was
dropping the include and showing only the name. Replace orcid.pdf includegraphics
and orcidlink with an iD text marker so the author line keeps a recognisable
ORCID cue. This is not the vector logo; it is a text approximation.

Test count is 1077.
2026-10-28 00:21:52 +08:00
gloamxun 8b742dacb3 Record Unicode table cells 2026-10-28 00:15:06 +08:00
gloamxun 37b956c0a6 Use Unicode math glyphs in table cells
Table conversion previously fell back to Size (um), approx. 100 and 10**6.
Emit µ, ~, ×, ±, Greek letters and Unicode superscripts instead, with ASCII
equivalents for width measurement when the CMR table lacks the glyph.

The arXiv table now reads Size (µm), ~100 and 10⁶ in both PDF and SVG; test
count stays 1076.
2026-10-28 00:14:55 +08:00
gloamxun fd9ee0740b Use Times metrics for bold and italic text
Add ptmb8t/ptmri8t/ptmbi8t metrics and TimesBold/TimesItalic/TimesBoldItalic
paragraph faces. A ptm document now maps Roman, bold, italic and bold-italic
base faces to the Times family, so headings and emphasised runs use Times
widths while the PDF backend continues to embed Liberation Serif.

The arXiv output is unchanged at 3 pages; previews measured 12.5-17.5 ms warm
and 191 ms cold. Test count is 1076.
2026-10-28 00:08:19 +08:00
gloamxun e9bbd4bd87 Use Times metrics for ptm documents
Add a merged ptmr8t TFM asset, a TimesRoman paragraph face and Cmr10Metrics
entry, map a ptm Roman paragraph to it, and select the Liberation Serif
TrueType PDF backend for those projects. The title is uppercased rather than
small-capped so its widths use Times metrics.

The arXiv PDF now embeds Liberation Serif for body text; title/author/abstract
land at y=88/173/277pt with three pages and all references. Headings and bold/
italic Times faces still use CMR metrics.

Test count is 1075.
2026-10-28 00:00:34 +08:00
gloamxun 2ef5e29329 Embed raster images in the SVG preview
The SVG preview painted every DisplayItem::Image as a grey rectangle. Encode
the raw RGB image as a PNG (zlib via flate2, CRC32, base64) and emit an SVG
<image> data URI; keep the grey fallback for images above four megapixels.

The article preview now contains the real 480x240 plot and the framed rule
figure is visible while editing. Test count stays 1074.
2026-10-27 23:50:48 +08:00
gloamxun fc328a56c6 Record the framed rule figure 2026-10-27 23:45:42 +08:00
gloamxun 13d0dd2fb7 Draw a framed rule body for fbox figures
A figure whose body is \rule now gets a small raster fbox approximation:
black frame, white gap and filled body, centred in the float. Image height is
already part of the float height, so the caption follows instead of overlapping.

The arXiv figure is now a centred framed square; it is still on page 2 while
TeX puts it on page 3. Test count stays 1074.
2026-10-27 23:45:30 +08:00
gloamxun 192788ec4b Record centred table floats 2026-10-27 23:42:39 +08:00
gloamxun 576626fe04 Centre table floats without losing rules or columns
The rule rectangle used width-margin for its right edge, so a centred table
shrank or lost its booktabs rules. Derive the right edge from the last column
offset instead, then centre a table float by shifting its margin. All three
columns and the rules now stay inside the measure.

Test count stays 1074.
2026-10-27 23:42:15 +08:00
gloamxun aa2f3cb0af Centre raster images inside floats
Add an x offset to VerticalItem::Image and use it when placing a decoded image
in a float, so a 0.4\textwidth plot is centred while its caption remains
centred across the float. Other image uses keep x=0.

Test count stays 1074.
2026-10-27 23:37:54 +08:00
gloamxun bbedf7676c Record working PDF image embedding 2026-10-27 23:30:40 +08:00
gloamxun d00402a745 Use pixel dimensions for PDF image XObjects
The display-list conversion stored the layout width/height (scaled points)
as PdfImage.width/height, so an image XObject claimed 12 million pixels and
pdfimages reported bad image parameters; the image never appeared. Keep the
layout rectangle in DisplayItem::Image but use the raster pixel dimensions for
the XObject.

Verified pdfimages now lists the 480x240 plot and the article PDF shows it.
Test count stays 1074.
2026-10-27 23:30:26 +08:00
gloamxun 16dd2e1f62 Count image height in float content
VerticalItem::Image was missing from Float::content_height, so image floats
reported zero content height and could overlap following text. Include the
image height and add a regression test.

Test count is 1074.
2026-10-27 23:21:52 +08:00
gloamxun c2310d85ac Emit author-year labels for project BibTeX
The project .bib inliner now derives author-year labels (with a/b
disambiguation for duplicate author-years) and writes them as optional
\bibitem labels. The route-D citation pass uses those labels only when they
look like author-year labels: \citep gets parentheses, \citet becomes
Author (Year), and reference entries lose their numeric brackets. Inline
thebibliography entries without such labels remain numeric.

The arXiv sample now prints (Kour and Saabne, 2014a; Keshet et al., 2016) and
Kour and Saabne (2014b), matching natbib semantics more closely. Test count
stays 1073.
2026-10-27 23:07:00 +08:00
gloamxun d2f0fe97c5 Refresh the figure limitation notes 2026-10-27 22:56:24 +08:00
gloamxun c5bf150449 Draw the rule body of fbox figures
Parse the first non-zero \rule{width}{height} in a figure without a decoded
image and use it as the float dimensions, so the arXiv sample gets its black
rule body instead of a caption-only float. The fbox frame and vector images are
still unsupported.

This changes the arXiv corpus preview to 3 pages, matching TeX; update the
corpus expectation. Test count stays 1073.
2026-10-27 22:55:52 +08:00
gloamxun 5c281d70cc Keep the last bibliography unit after the title spacer
The title spacer was inserted into base_units, but the paragraph/unit zip only
consumed paragraphs.len() units, silently dropping the final bibliography entry
(the third reference). Push the spacer directly into units and zip paragraphs
with the remaining base units instead.

Verified all three arXiv references are present again in the 3-page PDF; test
count stays 1073.
2026-10-27 22:42:09 +08:00
gloamxun a084845184 Record the post-author-column latency 2026-10-27 22:17:17 +08:00
gloamxun ca806341a8 Lay out arXiv authors in two columns
Encode \And author groups into a marker paragraph and build a centred two-column
halign instead of ten sequential lines. Footnote groups are extracted before
the table and reattached to the paragraph; literal ~ is normalized because the
CMR table font cannot cover it. The arXiv title page now puts the abstract at
y=279pt (TeX: 281pt) instead of ~431pt.

The generic \and join path is unchanged; its thanks test now asserts the
extracted footnote instead of a literal \footnote string.
2026-10-27 22:16:58 +08:00
gloamxun 6b89ab1dd7 Draw the arXiv title rules and undertitle
The arXiv class places 2pt rules above/below the title and an A Preprint
undertitle. Detect the class via its toptitlebar macro, reserve space with an
invisible rule (page builders discard glue before the first unit), and stamp
the rules/undertitle onto the first page for both preview and PDF.

Update the title-page header assertion: the first page legitimately carries the
undertitle, so it must lack the running center header instead. Author lines
remain sequential; two-column affiliations are still open.
2026-10-27 22:07:40 +08:00
gloamxun 7528ea26e2 Cache paragraph units across preview revisions
build_document was the real latency bottleneck (~196 ms), not page layout
(~2 ms). Add a bounded thread-local cache of laid-out normal paragraph units,
keyed by text, face, heading level, size, width and alignment, plus a full
paragraph-shaping geometry signature. Geometry changes clear the cache; floats,
tables, math and footnote-bearing paragraphs are not cached.

Release measurements after the cache: article-basic 47 ms, arXiv late edit
p50 57.5 ms / p95 70.3 ms (one page), 10-page simple stress document p50 13 ms
/ p95 14.7 ms. Cold first builds remain 150–370 ms. The 3-page and 10-page
measured cases now meet the <100 ms target; heading/front-matter edits still
reflow multiple pages.

The existing hang-indent server test caught a missing style field in the
signature; hang/looseness/fillskip/tolerance/penalty fields are now included.
Test count stays 1073.
2026-10-27 21:57:50 +08:00
gloamxun da30705cd0 Skip display lists for unchanged pages and profile the build
Patch previews now pass onlyPages into render_json before display-list
construction, so unchanged pages skip both glyph-list building and SVG
serialization. Late arXiv edits drop to p50 187 ms / p95 232 ms; article-basic
stays at 37.5 ms.

The gated profiler now reports build_done/layout_done. Release numbers show the
real bottleneck is build_document (~196 ms), while page layout is ~2 ms;
optimizing the page breaker will not reach <100 ms. Record that finding in the
roadmap. Test count stays 1073.
2026-10-27 21:41:56 +08:00
gloamxun d124c646a1 Serialise only changed pages for patch previews
render_json now accepts an optional page whitelist. The new
project_preview_patch_json_with_images path passes changedPages before building
page SVGs, instead of serialising all pages and filtering afterwards in the
server. Cache hits still use the old filter helper.

Add scripts/bench-preview.py: repeated buffer edits against a running server,
reporting HTTP/server latency, bytes and changedPages. Measure release builds:
article-basic 37.5 ms (one page), arXiv late edit p50 199 ms / p95 222 ms with
one changed page at 175 KB, arXiv heading edit ~480 ms. This is a solid
improvement over the debug numbers previously quoted, but the 10-page <100 ms
target remains unmet.

TEXRRA_PROFILE=1 now gates the geometry/paragraph/before-render timings. Test
count is 1073 (67 server).
2026-10-27 21:36:01 +08:00
gloamxun 9231c3a7d6 Return dirty-page preview patches
Project previews accept ?patch=1 and only include pages listed in changedPages.
Cache hits return an empty patch list. The web client applies sparse patches by
page index instead of rebuilding every page.

Add a two-page server test that edits only the second page and checks that the
patched payload contains exactly the changed page indices. Measure the arXiv
heading edit: 2 of 3 pages still changed (315 KB vs 396 KB full, 2.66 s), so
dirty-page transfer is in place but incremental layout latency is not.

Test count is 1073 (67 server).
2026-10-27 21:18:39 +08:00
gloamxun 86e95881e7 Lay out title and author blocks like the class
The title now uses the SmallCaps face, matching the class's \LARGE\sc title.
Author metadata is split on \and-row line breaks and \And author groups into
separately centred lines instead of one collapsed paragraph, with extra space
between author groups. This restores the visible author/affiliation structure
in the arXiv template while keeping the generic \and join for article authors.

Add a regression test for the title face, author line count and group spacing.
The author block is still sequential rather than the class's two-column
affiliation layout; title rules, ORCID icons and exact baseline spacing remain
open. Test count is 1072 (434 engine).
2026-10-27 21:10:46 +08:00
gloamxun e2e80e8728 Compile editor buffers without waiting for a save
Project preview accepts ?buffer=1 and reads the editor text from the POST body.
The source is still expanded with project includes/packages/images, but the file
on disk is not touched, so typing can drive layout immediately while the normal
450 ms save timer runs independently.

Add a server test that previews buffer text, finds it in the SVG, and verifies
hello.tex on disk was not rewritten. Roadmap notes that warm buffer previews
are still ~430 ms (article) and ~2.1 s (arXiv), and that dirty-page streaming
is the next latency step.
2026-10-27 21:01:24 +08:00
gloamxun 30f1df03ca Fix PDF page origin and add the fidelity/latency roadmap
The PDF writer received the raw geometry origin instead of the document's
effective offsets, so PDFs started at x=0 and clipped running headers above the
page even though the preview looked shifted. PDF output now uses the same
h_offset/v_offset as the preview.

For a geometry document with a 6.5in measure this restores the 1in text block;
the arXiv template's page-2/3 headers ("arXiv Template", "A Preprint") now
appear. A regression test checks the centred text block.

Add docs/TEX_FIDELITY_ROADMAP.md: page-frame/class/font/citation/math
fidelity workstreams, incremental revision/patch protocol, milestones and the
<100ms warm preview target. Test count is 1070 (433 engine).
2026-10-27 20:55:51 +08:00
gloamxun 7407d4ed42 Record the TeX Live comparison for the arXiv template 2026-10-27 19:14:23 +08:00
gloamxun b1e3e03f00 Fix the arXiv-template PDF output
The user-supplied template PDF exposed four concrete problems:

- title/headings were letter-spaced: plain text in a large paragraph took the
  SizedText segment path and was scaled twice; the fallback run now stays at
  the base size and is scaled once by the paragraph;
- the table lost its third column because unsupported math glyphs were sent
  through the PDF fallback font; table-cell math now has a readable ASCII
  fallback (Size (um), approx. 100, 10**6);
- fancyhdr's \cfoot{\thepage} was painted together with route-D's default page
  number; default numbering is skipped for a fancy pagestyle;
- .bib data was ignored; simple @article/@inproceedings entries are now parsed
  from project .bib files, inlined as thebibliography entries, and resolved by
  the existing citation pass, producing References and [1]-[3].

The regenerated 3-page PDF was checked for title/heading spacing, table text,
references and a single page number per page. A project regression test covers
the .bib path, and the table/heading fixes have unit tests.

Remaining visible limits in this template: the complex display equation, the
\fbox/rule figure body, vector/PDF images and the author block layout.
Test count moves to 1069 (444 core, 432 engine, 65 server).
2026-10-27 13:38:36 +08:00
gloamxun fab26234fc Discover a texrra-web sibling checkout
The repository is checked out as texrra-engine next to texrra-web, but
find_web_root only looked for ../web and ./web, so a plain
`cargo run --release -- serve examples/hello.tex 4174` served the "frontend not
found" page. The search now also accepts ../texrra-web and ./texrra-web, and the
startup warning names the sibling checkout. README and STATUS document the
accepted layouts.

Verified without TEXRRA_WEB_DIR: the server printed "Serving the web frontend
from ../texrra-web" and GET / returned the editor index.
2026-10-27 12:56:13 +08:00
gloamxun 254fd4a9a1 Fix heading/float block boundaries and record the web trial
The curated trial exposed two parser losses: a heading followed on the next
line by body text dropped the body, and consecutive figure/table/equation
blocks without blank lines swallowed each other. Headings are now separated
from following text and later headings, and the block splitter understands
display environments plus headings, so article-basic keeps its body, figure,
table and equation while arxiv-template moves from 2 to the expected 3 pages.

WEB_ROUTE_D_EXPERIMENT.md now records the three-project results (article-basic,
unicode-mixed, arxiv-template), the Edge smoke test, the go/no-go and the
updated P0 backlog: SVG preview image embedding, .bib data, vector figures and
table-cell math. Test counts move to 1065 (431 engine, 442 core, 64 server).
2026-10-27 12:46:48 +08:00
gloamxun 8d70868781 Record the web contract commit baseline 2026-10-27 12:24:52 +08:00
gloamxun 21943410e9 Refresh route-D counts and engine header note 2026-10-27 12:24:34 +08:00
gloamxun 1058122388 Add route-D web contract and experiment matrix
Route-D preview JSON now reports durationMs on the flat, project and edit
paths, and project preview/PDF responses carry X-Preview-Engine (route-d or
v1), including cache hits and silent fallback. The server tests assert the
headers, the duration field and both PDF engines.

docs/WEB_ROUTE_D_EXPERIMENT.md records the audit verdict, the initial contract
probe, the supported/gap matrix, the three-project trial plan and the
prioritised backlog; ROUTE_D_STATUS.md links to it and the test counts move to
1063.
2026-10-27 12:23:04 +08:00
gloamxun c49afbdecb Record the final verification run
The status document now records the final full run at commit a500236:
./scripts/verify-route-d.sh is fmt-clean and passes 1062 tests (442 core/route-D
unit, 429 engine binary, 63 server, 71 v1, 42 oracle, 10 route-D integration, 4
and 1).

No code changes in this increment.
2026-10-27 04:13:28 +08:00
gloamxun a50023691b Parenthesise eqref for non-equation labels
\eqref on a section, figure or table label rendered the bare number because the
section-reference pass shared the \ref replacement. It now wraps the value in
parentheses, matching amsmath's equation form; equation labels already took the
parenthesised path in the equation pass.

A preview test labels a section and checks "See (1)." with no warnings.
2026-10-27 04:11:45 +08:00
gloamxun 263fa36fb5 Activate dormant tests and clear route-D warnings
Three test functions in texrra-tex-core (PDF metadata, Type1 outline embedding
and \noalign row glue) were missing their #[test] attribute and only produced
dead-code warnings. With the attributes added they pass and raise the core suite
from 439 to 442 tests. The unused `mut` on the PDF entry point geometry is gone
too, leaving no route-D/PDF/lib compiler warnings in `cargo check
--workspace --all-targets`.
2026-10-27 04:09:26 +08:00
gloamxun c14c374d5d Consume FloatBarrier and balance
\FloatBarrier (placeins) and \balance (balance) were unsupported and could leak
into the body. Both are now removed in the body pass: flush requests are a
no-op because floats are already placed in source order, and column balancing
has no meaning in the single-column engine.

A preview test puts both commands between two paragraphs and checks the text
with no warnings or leaked commands.
2026-10-27 04:06:17 +08:00
gloamxun c89f972a25 Alias colours with colorlet
\colorlet{alias}{source} was unsupported, so a colour alias used by
\textcolor or \color leaked. The page-geometry pass now reads both brace groups,
looks the source up in the custom colours and the standard named colours, and
records the alias with the same RGB value.

A preview test defines an HTML colour, aliases it, colours a word with the
alias, and checks the RGB value reaches the SVG with no warnings.
2026-10-27 04:04:14 +08:00
gloamxun 7975671882 Give titlepage its own pages
A titlepage environment was unsupported, so a front-page block stayed in the
main flow. A body pass now replaces its begin and end with \newpage breaks
(trimming a leading break when the title page opens the document), and the
environment name counts as supported. The title layout itself remains the
content's responsibility.

A preview test puts a title page before the body and checks two pages with both
texts and no warnings.
2026-10-27 04:01:59 +08:00
gloamxun 0075352832 Record the route-D scope assessment
The status document now states what the handoff closes: the recovered commits,
the textual token/catcode engine, measured saveboxes, nested/valign tables,
NFSS/font coverage and the route-D service default, each backed by tests and
docs. It also makes clear that the Known limits are architectural extensions
that leave the corpus, oracle suite and service defaults green.

No code changes; verification stays at 1055 tests and the recorded live smoke
test.
2026-10-27 03:59:27 +08:00
gloamxun dff0483bca Add a verification script and record live smoke evidence
scripts/verify-route-d.sh runs cargo fmt --check and the full offline workspace
test suite from the repository root. The status document points at the script
and records a live check of the debug server: POST /preview answered 200 with
X-Preview-Engine: route-d, one page and no warnings, and POST /api/route-d/pdf
answered 200 with a PDF body.
2026-10-27 03:58:44 +08:00
gloamxun f71a12573e Consume multicols wrappers
A multicols environment was unsupported, so a template wrapping its body in
\begin{multicols}{2} leaked the wrapper and its count. A body pass now strips the
begin form (optional arguments and the column count) and the matching end, and
marks both environment names as supported; the body lays out at the full
single-column measure because the engine has no column balancing.

A preview test wraps two paragraphs in multicols{2} and checks both render with
no warnings and no leaked command.
2026-10-27 03:52:30 +08:00
gloamxun 59ba5ac247 Render the keywords environment
A keywords environment was unsupported, so classes that print their keyword
list as an environment leaked the wrapper. A body pass now finds the block,
replaces \sep with ", ", and emits a bold "Keywords:" lead-in followed by the
entries; the environment name counts as supported.

A preview test renders "alpha\sep beta" as "Keywords: alpha, beta" with no
warnings.
2026-10-27 03:50:14 +08:00
gloamxun 58c35c85b9 Resolve cref on equation labels
cleveref on an equation label still leaked: equation labels are resolved before
the section reference pass, so \cref/\Cref never saw them. The equation pass now
also rewrites both forms to "Equation <n>" in blocks and equation rows, matching
the existing \autoref handling.

The equation autoref test now also renders \cref{eq:a} and expects both
references.
2026-10-27 03:48:08 +08:00
gloamxun a451df620c Resolve cleveref cref lists
\cref and \Cref were unsupported, so documents using cleveref leaked the
command. The reference pass now scans both commands, splits the comma-separated
keys, looks each up in the existing label and kind tables, and joins them as
"Section 1 and Figure 1"; \Cref capitalises each kind and unknown keys become
"??".

A preview test labels a section and a figure and checks both forms with no
warnings.
2026-10-27 03:46:11 +08:00
gloamxun 25c7659afe Expand the common siunitx commands
\SI/\qty, \SIrange, \num and \si were unsupported, so numbers and units leaked
as command text. A body pass now reads their braced arguments, normalizes the
number (dropping thin spaces and grouping braces) and maps common unit macros to
short symbols: metre/meter to m, second to s, kilogram to kg, per to /, squared
and cubed to superscripts, and the kilo/milli/micro/nano/centi prefixes.

A preview test renders "3.5 m", "2 km/s", "1000" and a bare "m" with no
warnings.
2026-10-27 03:43:35 +08:00
gloamxun e53ce3b601 Support the appendices environment
The appendices environment was reported as unsupported, so appendix sections
kept main-matter numbering. A body pass now replaces \begin{appendices} with a
blank-line-padded \appendix (so it becomes its own block and the sectioning pass
sees it) and drops \end{appendices}; the environment name counts as supported.

A preview test puts a section inside appendices and checks "1 Main" and
"A Extra" render with no warnings.
2026-10-27 03:41:11 +08:00
gloamxun 82c3e24d18 Accept columnwidth and paper dimensions in graphics options
parse_image_length only recognized \textwidth, \linewidth, \hsize, \textheight
and \vsize, so width=\columnwidth (common in two-column templates) produced no
size. The list now also accepts \columnwidth and \paperwidth as widths and
\paperheight as a height, each scaling the configured measure.

The graphics sizing test gains a width=0.5\columnwidth case matching the
\textwidth result.
2026-10-27 03:38:44 +08:00
gloamxun f5ddad30a2 Support the usefont NFSS form
\usefont{encoding}{family}{series}{shape} was unsupported, so a class using the
low-level font selection left its arguments in the text. The inline NFSS parser
now recognizes the four braced groups, maps the family code through the same
cmss/lmss/phv/pcr/cmtt table as \fontfamily, and sets bold/italic/slanted/small
caps from the series and shape.

The existing nfss test gains an assertion that
\usefont{T1}{cmss}{b}{n} selects SansBold.
2026-10-27 03:36:08 +08:00
gloamxun c3aa4e9dad Parenthesise tag text like LaTeX
\tag{B} stored the bare text and the renderer painted "B", while LaTeX draws
"(B)"; \tag* is the bare form. Tag extraction now wraps the non-starred argument
in parentheses and leaves the starred form alone, for both equation rows and
whole equations.

The existing tag tests expect "(B)"/"(C)", and a new preview test checks the
parentheses glyphs around "A" with no warnings.
2026-10-27 03:33:21 +08:00
gloamxun 3b28ea6693 Accept starred equation tags
\tag* was not parsed: the tag extraction only looked for \tag, so the starred
form stayed in the formula. Both the row pass and the block pass now try
\tag*{...} before \tag{...}, so the tag text is removed from the math and used
as the equation tag.

A preview test tags an equation with \tag*{A} and checks the glyph appears with
no warnings and no leaked command.
2026-10-27 03:30:57 +08:00
gloamxun a5871774ec Resolve autoref on equation labels
\autoref{...} pointing at an equation fell through to "??" because equation
labels are resolved during the equation numbering pass and never reached the
section-reference kind table. That pass now also rewrites \autoref to
"Equation <n>" in both a math block and its equation rows.

A preview test labels an equation and checks "See Equation 1." with no
warnings.
2026-10-27 03:28:22 +08:00
gloamxun 4d713df3dd Resolve nameref for figure captions
\nameref fell back to the number for float labels because only headings fed the
title table. The float numbering pass now records each label with its raw
caption text, and that table is merged into the same title map nameref reads, so
\nameref{fig:a} returns "A plot" while \autoref keeps "Figure 1".

A preview test labels a figure with \caption{A plot} and checks
"See A plot and Figure 1." with no warnings.
2026-10-27 03:26:04 +08:00
gloamxun 8a5411af1d Expand counter formatting commands
\arabic, \roman, \Roman, \alph, \Alph and \value with a counter name were
unsupported and leaked into the text. The body pass now reads the braced counter
name and replaces the command with its stored value in the requested form,
using the same counter table that \setcounter/\stepcounter fill.

A preview test sets section to 4 and checks "4 iv D 4." with no warnings.
2026-10-27 03:24:00 +08:00
gloamxun 1d1009395b Offset counters with stepcounter
\stepcounter and \refstepcounter were unsupported, so a document that advanced a
counter before its next heading kept the old number. The geometry pass consumes
both commands and bumps the named counter in the stored counter table (creating
it at one when it was absent); page counters keep their dedicated
\addtocounter page handling.

A unit test steps section before \section{Introduction} and checks the heading
renders as "2 Introduction".
2026-10-27 03:21:48 +08:00
gloamxun 4068366190 Support xrightarrow and xleftarrow
The amsmath extensible arrows were unknown, so their labels fell back to plain
text. The math parser now reads \xrightarrow/\xleftarrow, an optional [below]
label, and the above label, and builds nested Stack atoms around the arrow
symbol: above stacks upward, an optional below label stacks downward.

The math test compares the bare arrow with the labeled form (width/height grow)
and with the two-label form (total height plus depth grows).
2026-10-27 03:18:20 +08:00
gloamxun 8307fc8918 Map boldsymbol to the bold math alphabet
\boldsymbol and \bm were unknown math commands, so a bold symbol fell back to
the default layout. Both names now select the same bold alphabet as \mathbf;
symbol-heavy arguments still use the regular symbol metrics, which is the
existing alphabet approximation.

A math test compares \boldsymbol{x} with \mathbf{x} for equal width and height.
2026-10-27 03:15:16 +08:00
gloamxun 3df130a6b3 Use short headings in running heads
A section's optional [short] title already replaced the long title in the table
of contents, but the running heads kept the long title. When recording heading
units, the document now prefers heading_short (with its number) and falls back
to the rendered heading text, so headings/myheadings and the fancy \rightmark
fallback show the short form.

A headings-style test with \section[Short]{A long title} checks the header says
"1 SHORT" and not the long title.
2026-10-27 03:11:56 +08:00
gloamxun 0e386f8fdc Respect myheadings marks-only headers
\pagestyle{myheadings} behaved exactly like headings, so it filled the left
header with the current numbered heading. The geometry now records myheadings
separately; in that style the left header shows the explicit \markboth/\markright
text when present and stays empty otherwise, while headings keeps using the
current heading title. The page number behavior is unchanged.

A two-page test sets myheadings and \markright{Custom mark}, then checks the
header shows "CUSTOM MARK" and not "1 INTRODUCTION".
2026-10-27 03:09:16 +08:00
gloamxun 4ad15f1f0b Give standalone labels their heading title
A \label on its own paragraph after a heading resolved \ref and \autoref, but
\nameref fell back to the number because the label-to-title table only recorded
labels taken from heading text. Section numbering now tracks the latest heading
title and records it for label-only paragraphs (and ordinary paragraphs that
carry a label), so \nameref returns the title for those labels too.

A preview test puts \label on its own line after \section, then checks
"Introduction and Section 1" with no warnings.
2026-10-27 03:07:12 +08:00
gloamxun abf5e90578 Capture tabulars wrapped in resizebox
A \resizebox or \scalebox around a tabular left the wrapper in the body and the
tabular capture swallowed the caption and \end{table}, so scaled tables were
lost. A source pass now removes such wrappers when their content contains a
table, longtable or table environment (and clears a leading % comment), leaving
the tabular at top level where the existing capture sees it; wrappers around
ordinary text stay for the later text pass.

A preview test wraps a two-row tabular in \resizebox inside a table and checks
"Table 1: Resized" plus the cell text with no warnings.
2026-10-27 03:05:03 +08:00
gloamxun e8f7e37cf7 Pin the corpus page counts
The corpus guard only checked that each document produced at least one page.
It now asserts the exact counts (hello 1, boxes 1, compat 1, arXiv template 2)
alongside the empty warnings array, so a layout regression that drops or adds a
page fails the server test even when no warning is emitted.

The status document's verification paragraph mentions the exact-count check.
2026-10-27 03:02:30 +08:00
gloamxun 7fbcb326d5 Keep the content of scaled box wrappers
\scalebox, \resizebox, \rotatebox and \raisebox were unsupported, so a wrapped
graphic or table could leak its command text. A body pass now parses each
wrapper's numeric/optional arguments and replaces the whole construct with its
content, leaving the content at natural size and position because the engine
has no display-list transform.

A test wraps four fragments in the four commands and checks the visible text
concatenates with no warnings and no leaked command names.
2026-10-27 02:59:19 +08:00
gloamxun dc9428e87e Honour explicit par paragraph breaks
An explicit \par inside a block stayed in the paragraph text and could leak as
an unsupported command. The final body pass now turns a standalone \par token
(not a \par... command prefix) into a blank line, so the block splitter starts a
new paragraph at that point.

A unit test feeds "First line.\par Second line." through geometry_and_body and
checks it splits into two paragraphs.
2026-10-27 02:56:28 +08:00
gloamxun 1227d82f02 Consume mark commands written inside running text
The line-start forms of \markboth and \markright were handled, but an inline
"Body \markright{Short title} text." leaked the command. A body pass now finds
either command anywhere, records the left/right marks for the running heads,
and removes the command from the text (malformed brackets are left untouched).

A fancy-header test puts \markright inside a paragraph and checks the header
shows "Short title" with no warnings and no leaked command.
2026-10-27 02:53:27 +08:00
gloamxun 5dda1a948a Give autoref the right kind prefix
\autoref always wrote "Section <number>", even for figure, table or theorem
labels. The reference passes now record a kind alongside each label: sections
use "Section", floats use their caption prefix (Figure/Table), and theorems use
their display name; resolve_section_refs builds \autoref from that kind, falling
back to "Section" for unknown labels.

A preview test labels a figure, refers to it with \autoref, and checks "Figure 1"
with no warnings.
2026-10-27 02:51:11 +08:00
gloamxun 48e86fb214 Close proof bodies with a QED symbol
A proof environment stopped at its last body line, without the boxed QED mark
LaTeX's amsthm draws. Proof bodies now get a trailing "□" (an explicit
\qedhere is consumed first), so the rendered result matches the usual proof
ending.

A preview test wraps "Because it follows." in a proof and checks the text ends
with the symbol and no warnings are reported.
2026-10-27 02:48:52 +08:00
gloamxun 1e4eb2d5ab Fall back to the current heading for fancy marks
Running heads expanded \leftmark/\rightmark only from explicit
\markboth/\markright, so a fancy header using \rightmark stayed empty when the
document never set a mark. Document now exposes the per-page heading list from
the previous increment, and running_head_text falls back to the current numbered
heading (uppercased) when no explicit left/right mark is configured.

A two-page test with \rhead{\rightmark} and a section checks "1 INTRODUCTION"
appears in the header with no warnings.
2026-10-27 02:46:34 +08:00
gloamxun 9da0f136a4 Show the current heading in headings-style headers
The headings page style only painted the page number. Document now records its
heading units (unit index and title) during layout, and a page_headings helper
carries the latest heading from page to page through the page sources. The
running-head pass uses that list in headings style: the numbered heading title
is uppercased at the left of the header and the page number stays right-aligned,
with the first page still plain.

The headings test gains a section and checks "1 INTRODUCTION" sits at the left
of the header baseline.
2026-10-27 02:44:14 +08:00
gloamxun ae810867f7 Cover nameref with a label on the next line
The heading-label fix and the title table interact: a label directly under
\section (no blank line) must still resolve \nameref to the heading title and
\autoref to "Section <n>". A preview test now pins that combination, rendering
"Introduction and Section 1" with no warnings and no "??".

No production code changed in this increment.
2026-10-27 02:40:54 +08:00
gloamxun 22d5332658 Put the page number in the header for headings style
\pagestyle{headings} and {myheadings} were ignored, leaving the number in the
footer. The parser now records the headings styles; the running-head pass paints
a right-aligned 9pt page number at the head baseline on pages after the first
(LaTeX's plain first page), and the footer number is skipped for those styles.
Section titles in the header are still not modelled.

A two-page preview test checks "2" sits above the body on page 2, right-aligned
past x=400, with no warnings.
2026-10-27 02:38:26 +08:00
gloamxun 9f642a2bbd Render custom bibitem labels
The optional label of \bibitem[Label]{key} was parsed and thrown away, so the
list and citations always used the running number. The extractor now carries the
label in the entry (behind a private marker) and the bibliography list prints
[Label]; citation resolution uses the same label for that key, while unlabeled
entries keep their positional number.

A preview test gives the first entry a label and leaves the second plain,
then checks the list markers and the two citation markers with no warnings.
2026-10-27 02:35:45 +08:00
gloamxun 85d5c87b12 Keep citation notes inside the brackets
An optional note on \cite, \citep or \citet was parsed and discarded. The
citation pass now remembers the first bracket note and appends it inside the
resolved bracket, so \citep[p.~3]{alpha} prints "[1, p. 3]" instead of "[1]"
(the tilde still becomes a space later in the text pipeline).

The existing citation test now asserts the note form; the rest of the unit
suite is unchanged.
2026-10-27 02:32:24 +08:00
gloamxun f05723808c Support explicit footnote numbers
\footnotemark[n] and \footnotetext[n]{...} left the bracket text in the line
and ignored the requested number. The footnote pass now reads an optional
bracketed integer: \footnotemark[n] emits that marker (and advances the counter
to it), while \footnotetext[n] attaches its body to the pending note with that
number, creating the entry when the mark appeared elsewhere in the paragraph.

A test uses mark and text with [7], checks "(7)" and the deferred body render
with no warnings, and that no "[7]" text leaks.
2026-10-27 02:30:01 +08:00
gloamxun d3baa78e1e Attach heading labels that follow on the next line
A \label on the line after \section without a blank line was discarded with the
rest of the text after the heading's closing brace, so \ref printed "??".
heading_command now keeps any immediately following \label groups (allowing
whitespace/newlines) in the heading text, which lets the numbering pass attach
them to that heading; other trailing text is still ignored as before.

A preview test puts \label{sec:intro} directly under \section{Introduction},
refers to it, and checks "See 1." with no warnings and no "??".
2026-10-27 02:27:17 +08:00
gloamxun 723b9e220f Render acknowledgement environments as a heading
The acks, acknowledgments and acknowledgements environments were reported as
unsupported. A body pass now rewrites their \begin into an unnumbered
"Acknowledgments" \section* and drops the matching \end, and the environment
names count as supported so the preview warning stays empty.

A test wraps "Thanks." in \begin{acks}, then checks the heading and body text
render with no warnings and no leaked environment names.
2026-10-27 02:24:23 +08:00
gloamxun 0a4bc0ade5 Handle cleardoublepage and column switches
\cleardoublepage was unsupported and \onecolumn/\twocolumn leaked into the
text. The block splitter now treats \cleardoublepage like \newpage/\clearpage
(it sets the pending page break) and consumes the two column switches, since
the engine lays documents out in a single column.

A test alternates the three commands around First/Second/Third, checks at least
two pages, all three texts present, and no leaked commands or warnings.
2026-10-27 02:21:01 +08:00
gloamxun c25c38f16a Resolve running marks in fancy headers
\markboth/\markright and the \leftmark/\rightmark placeholders were
unsupported. The page-geometry pass now consumes those mark assignments and
records the last left/right mark; the running-head text expands \leftmark and
\rightmark from that record (document-wide, not per page) before scrubbing, so
a fancy header or footer can carry the current short title.

A test sets \pagestyle{fancy}, \fancyhead[R]{\rightmark} and
\markboth{Left title}{Right title}, then checks the header text is
"Right title" with no warnings and no leaked \rightmark.
2026-10-27 02:18:11 +08:00
gloamxun 0728d78b29 Resolve nameref to heading titles
Section numbering now also records the heading title for each label: a
number_sections_with_titles variant fills a titles table (the existing
number_sections wrapper keeps its signature for tests), and
resolve_section_refs takes that table. \nameref{label} becomes the heading
title, falling back to the number when no title was recorded, while \autoref
keeps producing "Section <number>"; unresolved forms become "??".

A preview test labels a heading inside its braces and renders \ref, \autoref
and \nameref together as "1 and Section 1 and Introduction" with no warnings.
2026-10-27 02:15:13 +08:00
gloamxun c399481c6a Resolve autoref to its section number
\autoref was unsupported and leaked. The section-reference pass now rewrites
\autoref{label} to "Section <number>" using the same label table as \ref, and
unresolved autorefs become "??" with the other reference commands.

A preview test labels a heading inside its braces
(\section{Introduction\label{sec:intro}}), shows \ref and \autoref side by
side, and checks "1 and Section 1" with no warnings.
2026-10-27 02:12:21 +08:00
gloamxun 6139621653 Consume caption and numbering declarations
\captionsetup, \numberwithin and \DeclareCaption were unsupported and could
leak into the body. The page-geometry pass now consumes those declaration lines
(the caption styling and equation-number scoping are not modelled), in the
preamble and in the body alike.

A preview test declares \captionsetup (plain and with [figure]) and
\numberwithin before and inside the document, then checks "Text." renders with
no warnings and no leaked declarations.
2026-10-27 02:08:59 +08:00
gloamxun ebb178bff5 Reserve invisible space for phantom commands
Text-mode \phantom and \hphantom were unsupported. A text-stage pass measures
the scrubbed argument with the Roman metrics and replaces the command with
\hspace of that width, so the glyphs are omitted but the line keeps their
footprint; \vphantom contributes no horizontal material.

A test renders "A\phantom{wide}B and \vphantom{XX}C and \hphantom{QQ}D." and
checks "AB and C and D." with no warnings and none of the hidden text.
2026-10-27 02:06:20 +08:00
gloamxun 5fbcc34ddd Keep hyperref command labels
\hyperref[label]{text}, \hyperlink{name}{text} and \hypertarget{name}{text}
were unsupported and leaked as text. A text-stage pass now drops the link
machinery and keeps the visible label, accepting the optional [label] argument
of \hyperref and the braced target of the other two; internal PDF destinations
are not modelled.

A preview test uses all three forms and checks "the intro", "linked" and
"anchor" with no warnings and no leaked command names.
2026-10-27 02:00:35 +08:00
gloamxun 6c6963cac7 Support footnotemark and footnotetext
\footnotemark and \footnotetext were unsupported, so deferring a note body was
impossible. The footnote numbering pass now selects among \footnote,
\footnotemark and \footnotetext (longest name first so the prefix cannot win):
\footnotemark advances the counter, emits the numbered reference and records an
empty note for the number; \footnotetext fills that pending note with its body
and leaves no text in the line; the remaining text is appended once.

A test pairs a mark and its text in one paragraph, checks the page carries
"(1)" and "Deferred note." with no warnings, and that neither command leaks.
2026-10-27 01:58:22 +08:00
gloamxun 53a299bd58 Honour protect in edef but expand it normally
\protect was just a no-op token, so \edef\b{\protect\a} expanded \a at
definition time. In an edef-style pass the expander now copies \protect and the
following token unchanged (so the stored body keeps the protected command); in
the ordinary document pass it drops \protect and lets the token expand as
LaTeX does when the text is typeset.

A test defines a=A, \edef b={\protect\a}, redefines a=C, and checks both \b and
a literal \protect\a print C with no warnings.
2026-10-27 01:54:13 +08:00
gloamxun c3ae52452d Resolve csname targets with arguments
\csname foo\endcsname stopped after looking up a zero-argument macro; a
parameterised target was left unresolved. After the zero-argument fast path,
build a synthetic command from the resolved name plus the text following
\endcsname and run the normal macro lookup, so arguments/defaults/delimited
parameter text are consumed exactly as for a literal \foo, and only the bytes
belonging to the csname construct are charged to the caller.

A test defines \foo#1{[#1]} and prints both \csname foo\endcsname{x} and
\csname foo\endcsname{y} as "[x] and [y]" with no warnings.
2026-10-27 01:51:29 +08:00
gloamxun c3e02f0586 Make global definitions override group shadows
A group-local \def stayed visible after a later \gdef of the same name because
scoped lookup preferred the newest scope entry, and an inline \global\def was
unsupported. Route \gdef/\xdef and \global\def/\global\let/\global\chardef
through an upsert that removes same-name entries from every live scope before
updating the global table, so the global meaning wins inside the group and
after it.

A test defines a group-local L, replaces it with G via \gdef inside the group,
and checks the group prints G and the following \a prints G; an
inline \global\def also expands.
2026-10-27 01:49:17 +08:00
gloamxun 16b61cd368 Freeze unexpanded tokens through an edef
\unexpanded passed its text straight through, so \edef\b{\unexpanded{\a}}
expanded \a at definition time. Split the expander into an inner pass with a
freeze flag: the edef-style wrapper protects each backslash in \unexpanded's
argument with the existing no-expand marker, which the pass restores on the way
out, while the normal document pass still writes the text through so it expands
at use time.

A test defines a=A, \edef b={\unexpanded{\a}}, redefines a=C, and checks \b
prints C with no warnings; the earlier \expanded/\unexpanded/\detokenize test
still passes.
2026-10-27 01:47:08 +08:00
gloamxun 4024fa7435 Add the route-D status handoff and fix README defaults 2026-10-27 01:43:17 +08:00
gloamxun 8bdeffa646 Add expanded, unexpanded and detokenize
Three expansion primitives class files use were unsupported. \expanded{...}
runs the argument through the current macro table and scopes immediately;
\unexpanded{...} passes the text through unchanged (normal typesetting
semantics; the edef freeze is not modelled); \detokenize{...} prints the text
literally through the same private-use escaping as \string.

A preview test expands \a, passes \a through unexpanded and detokenizes it,
checking "Hi and Hi and \\a." with no warnings.
2026-10-27 01:41:52 +08:00
gloamxun 28aed153fe Guard corpus previews against warnings
The warning-free corpus sweep was only a manual check. Add a server test that
previews examples/hello.tex, boxes.tex, compat.tex and the arXiv template
through /api/route-d/preview and asserts each returns 200, at least one page
and an empty warnings array, so the corpus guard runs with the normal suite.
2026-10-27 01:39:32 +08:00
gloamxun 88a03ec1a1 Scale inline math proportionally
Inline math in a 12pt paragraph kept 10pt glyphs because paint_math advances
with 10pt metrics. Paint the math atom into a temporary display list at the
10pt baseline and scale that list as a unit (text sizes and positions, rule
widths/heights, line endpoints) to the paragraph size before translating it to
the baseline. The box no longer pins its size, so a scaled math glyph now
reports font-size 12.000 in a 12pt paragraph.

The twelve-point test now also asserts that an italic math glyph is rendered at
the paragraph size; the sized-paragraph test still expects a math box and no
literal dollars.
2026-10-27 01:36:59 +08:00
gloamxun b3fbbc8dda Render inline math in sized paragraphs
Inline math returned None whenever the paragraph base size was not 10pt, so a
12pt or \large paragraph printed its dollar delimiters literally. Keep the math
segment at every size: the box width still scales with the paragraph, while the
math glyphs are pinned to the 10pt metric baseline by setting the box's size
field, so paint positions and glyph sizes stay consistent (slightly smaller
than the surrounding text, which is documented).

The old sized-paragraph test now expects a math box and no literal dollars; a
new 12pt preview test checks italic math glyphs and no "$" with no warnings.
2026-10-27 01:34:07 +08:00
gloamxun 65a132d7b1 Handle parbox, orcidlink and a bare hrule
The last three corpus warnings: \parbox becomes an \mbox so the existing box
handling keeps its content (width wrapping is not modelled); \orcidlink{id}
becomes a hyperlink labelled ORCID; and a standalone \hrule becomes the same
here-float rule block as \rule, with the width left unset so the page builder
uses the current line width and a 0.4pt height.

The corpus sweep now reports 0 warnings for examples/hello.tex, boxes.tex,
compat.tex and the arXiv template.

A test previews parbox content, the ORCID link label and a bare hrule with no
warnings and no leaked commands.
2026-10-27 01:30:37 +08:00
gloamxun 93ecf76ea3 Clean inline spacing and guillemet text
A corpus sweep of examples/ and the arXiv fixture showed six warnings in
hello/compat and four in boxes: guillemet symbols, inline \vspace*, \samepage
and inline \smallskip/\bigskip. Add the four guillemet commands to the
text-symbol table and strip spacing commands that survive into running text
(their standalone forms already became vertical glue items, so only inline
leftovers are removed). The sweep is now 2/2/3 warnings (only \hrule, \parbox
and \orcidlink) and the arXiv fixture stays at zero.

Test: inline spacing, \samepage and guillemets render "ABCD«x»" with no
warnings.
2026-10-27 01:27:15 +08:00
gloamxun 7a9e28d0f4 Transpose valign into a table
\valign had no handler. Add a preprocessing pass that finds \valign{...},
splits the group at \cr, treats each remaining \cr-separated line as one column
(entries split on &), and emits an equivalent tabular with the matrix
transposed; the existing capture then lays it out. Column alignment defaults to
left because the \valign preamble describes vertical alignment here.

A test transposes \valign{\cr a & b & c \cr d & e & f \cr} into two columns and
three rows, checking (a,d) and (c,f).
2026-10-27 01:23:20 +08:00
gloamxun 05e1bd096b Apply the percent catcode when stripping comments
Comments were stripped in a separate pass before canonicalisation, so
\catcode`\%=12 happened too late to make a later percent literal. Move comment
stripping into the canonicalisation pass: it now tracks whether % is a comment
char (default yes), skips to the end of line when it is, and \catcode`\%=12
(or 13) turns that off so later percents reach the text. The source order in
geometry_and_body becomes canonicalise (comments + catcodes) then collapse
definition bodies, and the separate strip_tex_comments call is gone.

A test previews "100% sure" under \catcode`\%=12 and the default commented form
("Hello% hidden" + "world") as "Helloworld" with no warnings.
2026-10-27 01:21:10 +08:00
gloamxun d791e3a0f2 Print macro bodies with meaning
\meaning<token> was unsupported. Expansion now reads the following token and
prints its meaning literally: for a known macro, "macro:" plus its parameter
text (or #1..#n from the argument count) and "->" plus the stored body; for an
undefined control sequence, \relax; for a character, "the character <c>". The
text goes through the same private-use escaping as \string so later passes
cannot re-tokenise it.

A preview test defines \greet#1 and prints \meaning\greet plus
\meaning\missing, checking "macro:#1->Hello #1" and "\relax" with no warnings.
2026-10-27 01:18:49 +08:00
gloamxun 47dcdfec47 Print tokens literally with string
\string<token> was unsupported, so documenting a control sequence expanded it
instead of printing it. The expand loop now reads the following token and emits
its characters without expansion; backslash and braces are replaced by
private-use placeholders that the renderer maps back to the real characters, so
the printed text cannot be re-tokenised and expanded by a later pass.

A preview test defines \foo, prints \string\foo, \string{ and \string}, and
checks the literal "\foo and { and }." with no expansion of \foo and no
warnings.
2026-10-27 01:16:30 +08:00
gloamxun 57424015de Measure image saveboxes from decoded pixels
A savebox whose body was only \includegraphics measured as empty text because
images were attached to the geometry after geometry_and_body had measured the
box. geometry_and_body_with_images now seeds the image map before stripping, so
measure_savebox sees the decoded RasterImage: natural size is pixels at 72 dpi
(65,782 sp per pixel), and explicit width/height options in the optional
argument win, with the other dimension scaled proportionally.

Project preview/PDF paths pass their decoded images into the new entry point;
the flat preview keeps the empty map. The body-definition capture only handles
\newsavebox, so its call passes an empty map too.

A test stores a 100x50 image in \logo and checks the frozen width/height and a
zero depth.
2026-10-27 01:14:02 +08:00
gloamxun 53dcedfea2 Refresh the limits section after thirty increments 2026-10-27 01:10:12 +08:00
gloamxun 2ef284e585 Add token registers
\toks was unsupported, so \newtoks/\toks0={...}/\the\toks0 leaked. Expansion
now carries a token-register table next to the macro table: \newtoks declares a
named register, \toks0={...} and a declared \name={...} store text, and
\the\toks0 or \the\name splice the stored text back into the stream.

A preview test stores Hello in a named register and A in \toks0, then renders
"\the\greet and \the\toks0 B" as "Hello and A B" with no warnings.
2026-10-27 01:08:56 +08:00
gloamxun 9005194c54 Rescan scantokens content through the expander
\scantokens was unsupported and leaked its group. Handle it in the expansion
loop: parse the braced argument, replace the command with the group text (after
the command-end marker so it cannot merge with a preceding control word), and
let the remaining passes re-tokenise and expand it like ordinary source.

A preview test defines \greet, runs \scantokens{\greet world}. and checks
"Hello world." with no warnings and no leaked command.
2026-10-27 01:06:40 +08:00
gloamxun cc00b6332c Correct catcode docs wording 2026-10-27 01:04:43 +08:00
gloamxun 54a0926552 Consume catcode assignments for every character
Only \catcode`\@ assignments were handled; a class file setting the catcode of
# or _ left the assignment in the text. The canonicalisation pass now consumes
any successfully parsed \catcode assignment (backtick, bare or code-point
target), applying the value only to @ (11/12); other targets are recorded by
their consumption but do not change scanning yet, since the scanner still has
a single modelled catcode.

A preview test sets # and _ to 12, then renders "#hash and a_b." with no
warnings and no leaked assignment.
2026-10-27 01:04:23 +08:00
gloamxun b16e5a53e8 Run afterassignment tokens after their assignment
\afterassignment<token> leaked because assignment processing happens in later
passes. Add a rewrite after the body is extracted: find \afterassignment, read
its token, locate the following assignment (a \def/\gdef through
runtime_definition, or the next top-level '=' plus its value token), and move
the command before the assignment's follower so the assignment passes run
first. The queued token stays in the stream for normal expansion.

A preview test queues \hello before \a=5 and checks H appears, Text. still
renders and no \afterassignment leaks.
2026-10-27 01:01:28 +08:00
gloamxun 24d5390d25 Queue aftergroup tokens until the group closes
\aftergroup was unsupported, so class-style deferred setup leaked. Expansion
now keeps a parallel stack of pending token lists: '{' and \begingroup push an
empty list, '}' and \endgroup pop it and append its tokens after the group (the
closing brace is emitted first, then the pending tokens with the command-end
marker so a control word cannot merge with the following text).
\aftergroup<token> queues one token and \aftergroup{...} queues the group body.

A test defines a group-local \a while queueing \aftergroup\a, then checks that
the queued \a runs after the group restores A, giving "AA and !X" with no
warnings.
2026-10-27 00:59:19 +08:00
gloamxun 9d10def2f5 Add futurelet lookahead and defer conditionals
\futurelet\alias\command <token> now binds <token> to \alias without consuming
it: the expand loop parses the alias and command, stores the peeked token as the
alias body, and leaves the command plus token in the stream. Conditional
operands are protected from macro expansion, so \ifdefined and \ifx still see
the names they test, and a token-alias macro whose body is one character
compares equal to that character in \ifx.

Conditionals moved after macro expansion (and before register expansion):
running them first evaluated \ifx inside a not-yet-expanded \def body, and
register expansion turned the \a in \ifnum\a=3 into an assignment. The
expand_macros_mut variant writes its runtime table back so later passes see
\futurelet aliases and runtime definitions.

A test covers \futurelet\next\shownext x printing [x] and an \ifx dispatch that
chooses Y.
2026-10-27 00:56:33 +08:00
gloamxun e48a64da7a Resolve csname during runtime expansion
\csname only worked inside \edef bodies, so a normal macro such as
\def\a{\csname foo\endcsname} leaked the literal construct. Handle it in the
expand loop: read through \endcsname, expand the inner text with the current
runtime table and scopes, look the resulting control sequence up, and splice
its body (nothing when undefined). Macro arguments are not consumed, so a
parameterized target is left alone for now.

A preview test defines \a through \csname, uses both \a and a direct
\csname foo\endcsname, and checks "Z and Z and ." with no warnings.
2026-10-27 00:49:07 +08:00
gloamxun 34d54d91a4 Honor \catcode`\@ assignments
Class files often set the @ catcode directly instead of calling
\makeatletter. Recognise \catcode assignments in the canonicalisation pass for
the @ target: the target may be written with a backtick, bare, or as a code
point, the value must be numeric (11 letter, 12 other) or \active, and the
assignment is consumed and updates the same state \makeatletter toggles.
Assignments for other characters are left untouched so nothing is silently
dropped.

A preview test sets \catcode`\@=11, defines and uses \@foo, and checks "bar"
with no warnings and no leaked assignment.
2026-10-27 00:46:15 +08:00
gloamxun b056b11ba9 Expand parameterized runtime definitions
runtime_definition only accepted \def\name{body}: if the first token after the
name was not '{' it gave up, leaving a body-embedded \def\foo#1{...} to leak as
text. Parse the parameter text before the body with the same helpers the line
capture uses: definition_argument_count for undelimited #1..#n, otherwise
parameter_placeholders plus the raw parameter text for delimited forms. The
returned MacroDefinition carries args/params, so expand_macro_lookup collects
the arguments during expansion.

A preview test defines \add#1 and \pair#1,#2 mid-body and checks "[x]" and
"(a|b)" with no warnings.
2026-10-27 00:43:51 +08:00
gloamxun 619eb19f72 Map fontspec families to engine faces
fontspec declarations were neither consumed nor mapped, so
\newfontfamily\headingfont{...} leaked into the text. Consume \setmainfont,
\setsansfont and \setmonofont (the engine's Roman/Sans/Mono faces stand in for
those choices) and turn \newfontfamily/\renewfontfamily into an alias macro that
switches to the closest NFSS family by name: mono/typewriter/courier to cmtt,
sans/helvetica/arial to cmss, otherwise cmr. Optional bracket options are
skipped.

A preview test declares all four commands, renders \headingfont Sans words. and
checks no warnings, the sans-serif face and no leaked declaration text. Docs
also record that complex scripts (Devanagari, Thai, emoji) still have no shaping
fallback and render as missing glyphs in the PDF.
2026-10-27 00:41:36 +08:00
gloamxun 81da180ab7 Lay out nested tables inside their cell
Nested tabulars were flattened to a text summary before the outer halign
parsed them, so the inner rows never existed as a table. Keep them instead:
strip_page_geometry replaces each nested block with a \texrranested{index}
token and stores the source on the geometry, and tabular_unit resolves the
token into a recursively built inner table attached to the cell. Cell text is
cleared, column widths and row height take the inner table's metrics, and page
splitting remaps nested row indices when it chunks rows.

Halign gains a nested list, refresh_measurements, nested-aware row_height and a
painting branch that translates the inner display list to the cell position at
the row's alignment. The old flattening pass stays as a dead-code fallback.

The nested-table test now checks one stored source, the placeholder token, one
attached 2x2 table in cell (0, 1), an empty outer cell and inner "a"/"d"
painted in the preview SVG.
2026-10-27 00:38:02 +08:00
gloamxun 371f05baaa Default project previews and PDFs to route-D
uses_route_d still treated v1 as the default unless TEXRRA_ENGINE=route-d was
set, so only the flat /preview endpoint had switched. Make route-D the default
there too: an explicit engine parameter still wins, TEXRRA_ENGINE=v1 forces the
old pipeline, and a route-D error now falls through to the v1 compiler instead
of answering 422 (both preview and PDF).

Because route-D follows pdfLaTeX's Letter default for geometry-less documents,
the two server tests that asserted the v1 A4 page now ask for ?engine=v1 or
expect 215.9mm. A new test starts a server without the environment variable and
checks a project preview uses route-D's italic math face with no literal $.
2026-10-27 00:32:45 +08:00
gloamxun a56d441513 Make route-D the default flat preview engine
POST /preview served the v1 pipeline while route-D lived behind /api/route-d
and the project engine switch. Try route_d::preview_json first and keep the v1
compiler as the fallback when route-D rejects the source; ?engine=v1 forces the
old path and the project endpoints are unchanged.

Both paths now answer with an X-Preview-Engine header (route-d or v1) so the
choice is observable, and the server test helper compares header names
case-insensitively because tiny-http lowercases them.

A server test posts a document and checks route-d by default plus v1 when the
query asks for it.
2026-10-27 00:27:59 +08:00
gloamxun 621a8abb92 Make @ a letter only inside makeatletter
The scanner treated @ as a letter everywhere, so \makeatletter was a no-op and
\foo@bar parsed as one command even outside it. Canonicalise the source once,
before captures: in the default state a control word stops at @ (and a marker
keeps later scanners from re-joining the split), between \makeatletter and
\makeatother the name is rewritten with a private-use placeholder that
control_sequence and expand_macro_lookup accept as a letter and normalise back
to @. Grouping saves and restores the state, and route-D's own \@... names plus
the internal \p@/\z@/\protected@edef family stay literal so their handlers keep
matching; markers are stripped from text before shaping.

Tests cover \@foo inside makeatletter, \foo@bar splitting to \foo plus "@bar",
\@ifundefined still working, and a group-local \makeatother.
2026-10-27 00:24:28 +08:00
gloamxun d4de3a3f35 Expand body edef definitions when they are read
\edef/\xdef were expanded eagerly only in the preamble: after \begin{document}
the strip pass no longer captured definitions, and capture_body_definitions had
no edef branch, so a body \edef\b{\a} stored the raw body and expanded \a later.
The body branch now calls edef_definition (which also resolves \csname), and the
strip pass leaves body edef/chardef lines to it instead of swallowing them.

A test with \begin{document} defines a=one, \edef b={\a}, redefines a=two and
expects "one and two"; the existing preamble edef/xdef tests still pass.
2026-10-27 00:19:28 +08:00
gloamxun 9aa743b601 Run let/chardef and keep group definitions local
Runtime expansion only understood \def/\gdef. Add \let\alias=\target (a macro
body that expands to the target) and \chardef\name=<code> (a one-character
body), both honoring the current scope, so class-style aliases work and can be
shadowed inside a group.

Line-based capture also still pulled a definition line out of a group and made
it global. Track brace depth across body lines and only capture at depth zero,
and restrict strip_page_geometry's definition capture to the preamble before
\begin{document}; body lines now reach runtime expansion where the scope stack
applies.

Tests preview a group-local \def on its own line as "twoone" and
\let/\chardef as "HiandA".
2026-10-27 00:15:20 +08:00
gloamxun d1b66af251 Scope runtime definitions to their group
Expansion kept a single flat macro table, so a \def inside {...} replaced the
outer definition for the rest of the document. Keep a scope stack in
expand_macros instead: '{' and \begingroup push a scope, '}' and \endgroup pop
it, and lookup walks the scopes newest-first before the document table. A
top-level \def and every \gdef update the document table; a \def inside a group
only shadows until the group closes.

Runtime \def\name{body} is now parsed during expansion (the pre-expansion inline
capture is gone), and grouping braces are dropped after command parsing so the
scope braces do not print: plain pieces, link labels, inline runs and the
fallback face path all strip them at that point.

A test previews \def\a{one}{\def\a{two}\a}\a as "twoone" and the
\begingroup form likewise; the existing inline-definition test still passes.
Catcode state and a real token stream remain open.
2026-10-27 00:10:18 +08:00
gloamxun 7547c0abc4 Capture inline definitions and @ control words
The line-based capture treated any line that began with a definition command as
a definition and dropped the rest of the line, so
\makeatletter\def\@foo{bar}\makeatother\@foo lost everything after the body.
Only consume such a line when the definition actually ends it; otherwise leave
it for a new inline pass that captures simple \def\name{body} forms anywhere in
running text.

\makeatletter/\makeatother are stripped as no-ops and the macro expander now
scans @ as a letter, matching control_sequence, so \@foo expands to its body.

A test defines \@foo and \greet in one body line and checks the previewed text
"bar and Hello." with no warnings. Group scoping, catcode state and a token
stream remain open.
2026-10-27 00:02:54 +08:00
gloamxun def93b6cf5 Keep nested tabulars inside their outer table
The table capture ended at the first \end{tabular}, so a nested table inside a
cell closed the outer table early and the remaining inner rows leaked into the
document. Track the nesting depth of \begin{tabular}/\end{tabular} and only
close the outer environment at depth zero.

Nested blocks are flattened before the outer halign parses them: inner rows are
split on \\ and cells on &, rule commands and \multicolumn/\multirow wrappers
are stripped, and the text is joined as "a b ; c d" inside the outer cell. The
outer structure, column count and row count survive; true nested-table layout
and \valign remain open.

A regression test wraps a 2x2 tabular in a 2-column outer table and checks one
captured table, two columns, two rows and the flattened inner text.
2026-10-26 23:56:43 +08:00
gloamxun 4b28d65006 Render Greek math commands as their letters
\alpha through \omega, the uppercase Greek commands and the varepsilon /
vartheta / varrho / varsigma / varphi / varpi / varkappa variants were not in
the math command table, so a formula such as $\alpha+\beta$ painted "?" glyphs.

Map them to their Unicode code points. The math renderer already treats the
Greek ranges as math letters and sends them through the math-italic fallback,
so the formula now previews as α+β=γ with no warnings; the widths still use the
TFM fallback constant rather than per-letter cmmi metrics.

A core test pins the parsed symbols and a route-D test checks the previewed
characters.
2026-10-26 23:52:44 +08:00
gloamxun 5a1a04d029 Freeze savebox metrics and expand wd/ht/dp
\sbox/\savebox now measure their content at definition with the Roman metrics
at the class base size and store width/height/depth. \usebox carries that size
into the no-break segment, which scales the box back to its definition size
inside a differently sized paragraph, and \wd/\ht/\dp\boxname expand to the
frozen metrics before paragraph parsing.

\mbox/\hbox/\makebox keep following the surrounding size (their marker carries
size 0). A core test checks that a box frozen at 20pt is twice as wide as the
10pt one, and a route-D test checks the measured dimensions and a
\hspace{\wd\box} expansion. Image-only boxes still measure as empty text.

Three savebox tests strip the internal markers (now with their size prefix)
before comparing visible text.
2026-10-26 23:48:42 +08:00
gloamxun 95a6a1291a Keep mbox and savebox content on one line
Add InlineSegment::NoBreak: it shapes each word and replaces the interword
glue with fixed-width boxes, so the run has no breakpoints and behaves like
TeX's unbreakable hbox rather than reflowing at the use site.

Route-D wraps \usebox bodies and \mbox/\hbox/\makebox arguments in private-use
markers; the paragraph text builder splits on them and emits NoBreak runs,
leaving ordinary text and styling on the existing path. \underline keeps its
old inline behaviour.

A 60pt measure now keeps \mbox{alpha beta gamma} and a stored
\sbox{alpha beta gamma} on one line, covered by a core segment test and a
route-D test. Savebox dimensions are still measured at the use site instead of
being frozen at definition, and \wd/\ht/\dp accessors remain open.
2026-10-26 23:43:53 +08:00
gloamxun 56faec6046 Split colour, link and sized runs at any base size
inline_math_segments returned None for every paragraph whose base size was not
10pt, so a 12pt or \Large paragraph kept \textcolor/\href/\textsuperscript
delimiters as literal text. Only inline math actually depends on the 10pt
metric baseline: build the segments at any size and fall back to literal
delimiters only when a math segment is present and the size differs.

The existing sized-href test moves from "href is stripped but not linked" to
"the sized run keeps its link", and a new 12pt test covers a red run, a link
and a superscript in one paragraph with no warnings.
2026-10-26 23:37:14 +08:00
gloamxun 15b5437987 Paint fancyhdr running heads and feet
Parse \pagestyle{fancy}, \fancyhf, \fancyhead/\fancyfoot with L/C/R positions,
the \lhead/\chead/\rhead/\lfoot/\cfoot/\rfoot shorthands and
\renewcommand{\headrulewidth}, and paint them on every page. Head fields are
placed at top margin - \headsep and feet at text height + \footskip, both in
content coordinates so the page origin shifts them with the body; left, centre
and right align against the text measure, \thepage is expanded per page, and
the head rule uses the requested width.

Size and shape declarations are stripped before macro expansion because class
files define \footnotesize in terms of itself; expanding it repeated
\@setfontsize internals on every pass. A title page with fancy style is treated
as \thispagestyle{empty}, matching class \maketitle definitions.

The arXiv template now shows "A Preprint" on the right and its short title in
the centre after the title page, with the page number in the footer; tests
cover field parsing, painted positions/alignment and the title-page
suppression.
2026-10-26 23:32:52 +08:00
gloamxun 7a615a8639 Place the page body below geometry's top margin
The geometry package's top/bottom margins were only used to derive a text
height; the laid-out body still started at the very top of the sheet, so the
arXiv template's 1in top margin was ignored and text sat on the paper edge.

Record top/bottom margins on PageGeometry and add the top margin to the page
body's vertical offset, which both the SVG preview and the PDF writer honour;
the page number and footer baseline move with the body. An explicit textheight
still wins over the margin-derived one.

The arXiv template's first baseline now sits at 1in + 12pt, still with zero
warnings in two pages. Unit tests cover the margin parse/derive and a preview
whose first baseline shifts by exactly one inch.
2026-10-26 23:25:20 +08:00
gloamxun 21d48866de Preview the arXiv template without warnings
The archived class file expands \maketitle, \section and \keywords into LaTeX
internals that route-D does not model, so the template's title block, headings
and keywords were replaced by LaTeX machinery and 20+ control words reached
layout.

Keep \maketitle, \thanks and the heading commands out of generic macro
expansion so the native title block and section parser see them; scrub the
author metadata (\href labels, ORCID \includegraphics, text-style wrappers,
line breaks and \And) into plain text; turn \keywords into a "Keywords: ..."
paragraph; expand \lipsum[n]/[a-b] to filler paragraphs; drop `%` comments and
external \bibliography/\bibliographystyle commands (an inline thebibliography
still supplies References); and start a new block when center/flushleft/
flushright follows text on the same chunk.

The arXiv fixture now previews with zero warnings in two pages, covered by a
JSON-level regression test. Remaining class support is still semantic rather
than a TeX VM.
2026-10-26 23:20:58 +08:00
gloamxun 1b7baa0257 Capture multi-line macro definitions and mode conditionals
The preamble parser is line-oriented, so a multi-line \newcommand, \def or
\newenvironment contributed only its first line to the macro table while the
remaining body lines fell through to the document text. In the assembled arXiv
source that also swallowed the \begin{document} marker, so the whole class
preamble was laid out as one page of \NeedsTeXFormat/\fancyhf text.

Join definition bodies at balanced braces before stripping: comments are
removed, a `%` line continuation joins without adding a space, and a blank line
becomes \par. Definitions now reach the existing single-line capture whole.

Resolve \ifhmode as true and \ifvmode/\ifmmode as false for the text expansion
path, so class macros such as \and expand.

The arXiv fixture body no longer contains NeedsTeXFormat, fancyhf or ifhmode and
the project preview lays out four pages instead of one; unit tests cover a
multi-line \newcommand/\def and the arXiv preamble containment. Remaining
warnings are now body commands (\maketitle, \thanks, \lipsum, \addvspace and the
footnote machinery), which are separate work.
2026-10-26 23:08:35 +08:00
gloamxun ebf2070295 Run AtBeginDocument setup and newgeometry as preamble
Class files such as the arXiv template set the page block inside
\AtBeginDocument{\newgeometry{...}}. Route-D treated the hook body as document
text, so the setup commands were typeset at the top of page one and the page
measure stayed at its default.

Lift \AtBeginDocument bodies in front of \begin{document}, join a multi-line
\newgeometry argument into one line, and read it through the geometry option
parser. Explicit textheight/textwidth options now win over margins, so
textheight=9in with top=1in keeps 9in instead of recomputing it from the
paper height.

The arXiv project now applies its 6.5in/9in block and no longer reports a
\newgeometry warning; unit tests cover the multi-line hook, the option
precedence, and the no-leak case. A remaining leak from multi-line macro
definitions in the same class file is separate work.
2026-10-26 23:03:37 +08:00
gloamxun 2f9b18c95c Reserve display skips around math
TeX surrounds each display with \abovedisplayskip above and \belowdisplayskip
below, but route-D only reserved the paragraph's own spacing, so displays sat
directly against the surrounding text. Parse the four registers (including the
short forms), default to the article-class 10/11/12pt values, and add them to
the math unit and the unit that follows it.

The glue parser now also accepts the class-file spelling
(`\abovedisplayskip 7\p@ \@plus 2\p@ \@minus 5\p@`), register copies such as
`\belowdisplayskip \abovedisplayskip`, `\z@`/`\p@` dimensions and
space-separated assignments, which clears the display-skip warnings the arXiv
template produced.

A page oracle sets a 45pt above skip and pins the display moving to the second
page exactly as pdfLaTeX lays it out; unit tests cover the defaults, overrides
and the class-file spelling.
2026-10-26 22:49:41 +08:00
gloamxun 8ac2e828df Honour club and widow penalties on paragraph lines
Route-D expanded a paragraph into one node per line without TeX's
\clubpenalty/\widowpenalty, so a page break could orphan the first line or
widow the last. Insert the penalties between line nodes (150 by default, read
from the source registers) and make the page builder reject any penalty of
10000 or more as a breakpoint. Forced -10000 values now break exactly where
pdfLaTeX does; two page oracle fixtures compare per-page text, and unit tests
cover the node order and the forbidden breakpoint.
2026-10-26 22:14:01 +08:00
gloamxun 1bb28cf141 Skip the SIVP test when its project fixture is absent
projects/ is gitignored, so a fresh clone has no projects/_sivp__/sn-article.tex. Return early like the neighbouring front-matter test instead of panicking on the missing file.
2026-10-26 22:03:25 +08:00
gloamxun 83f49db49e Sort oracle word boxes before grouping lines
pdftotext 26 does not always emit words in reading order: wide justified gaps and hyphenated lines interleave words from different baselines, so parse_bbox split one visual line into several. Sort by baseline and then x before grouping. It also reports each word box as the font extent, whose ascent varies with type size; compare display limits by the subscript/superscript baseline gap, which is anchor-free, instead of mixing 7pt box tops with the 10pt base.
2026-10-26 22:03:25 +08:00
gloamxun e09e413892 Break long paragraphs with prefix sums
The line-breaker rescanned items[start..end] for every break pair, so a 900-word paragraph took seconds and the 2,700-word edit fixture took about 30 s. Prefix sums over natural width, stretch, shrink, glue order, box count and the last penalty give each candidate its metrics in O(1); the search now costs O(breakpoints^2) and the same document lays out in about 0.3 s. Add a 900-word regression test and note the change in TEX_CORE.
2026-10-26 22:03:19 +08:00
gloamxun 41c68baa5d Ignore display break hints 2026-10-26 20:37:24 +08:00
gloamxun 7271e2ee12 End table rows with tabularnewline 2026-10-26 20:36:57 +08:00
gloamxun 80a5e8272d Stretch tabular* tables to their target width 2026-10-26 20:36:49 +08:00
gloamxun 3770de0804 Render tabular* by its declared column template 2026-10-26 20:36:43 +08:00
gloamxun 40abb7bef3 Reserve environment definitions declared in the body 2026-10-26 20:36:30 +08:00
gloamxun 0d9ed56a55 Reserve theorem definitions declared in the body 2026-10-26 20:36:21 +08:00
gloamxun 3087a9a116 Reserve saveboxes declared in the body 2026-10-26 20:35:58 +08:00
gloamxun eaebb1edbf Reserve registers declared in the body 2026-10-26 20:35:42 +08:00
gloamxun 13de893c46 Capture body-level newif definitions 2026-10-26 20:35:34 +08:00
gloamxun dc49b92a47 Capture body-level chardef definitions 2026-10-26 20:35:09 +08:00
gloamxun 2408736c5e Capture body-level let aliases 2026-10-26 20:34:44 +08:00
gloamxun 6efb210781 Capture definitions written in the body 2026-10-26 20:34:33 +08:00
gloamxun 1d891b2c6a Verify test server identity before accepting it 2026-10-26 20:34:20 +08:00
gloamxun 7c98c61b7a Ignore preamble-only guards 2026-10-26 20:34:06 +08:00
gloamxun 991498b0e1 Guard definitions with @ifdefinable 2026-10-26 20:33:57 +08:00
gloamxun f6a41c9f59 Expand the checkmark symbol in text 2026-10-26 20:33:49 +08:00
gloamxun 8e884e6db1 Expand parameterised newcolumntype letters 2026-10-26 20:33:43 +08:00
gloamxun 9d57ca604e Expand newcolumntype letters in table specs 2026-10-26 20:33:14 +08:00
gloamxun 97e883f51d Branch on @ifclassloaded for supported classes 2026-10-26 20:33:02 +08:00
gloamxun c9982a7675 Branch on @ifpackageloaded for known packages 2026-10-26 20:32:51 +08:00
gloamxun fce3a3b0a0 Honour optional newenvironment defaults 2026-10-26 20:32:41 +08:00
gloamxun b7d18dff37 Expand punctuation and symbol commands 2026-10-26 20:32:18 +08:00
gloamxun 3a089c6175 Number standalone captionof captions 2026-10-26 20:32:01 +08:00
gloamxun 7d05268983 Keep underline text without the rule 2026-10-26 20:31:45 +08:00
gloamxun f147ccc8c5 Parse array column modifiers and their alignment 2026-10-26 20:31:33 +08:00
gloamxun 71dc8ca59b Treat starred floats as their single-column forms 2026-10-26 20:31:18 +08:00
gloamxun 8ecbd5e720 Centre multirow cells over their rows 2026-10-26 20:31:03 +08:00
gloamxun e039cfb8a9 Report float and equation pages through pageref 2026-10-26 20:30:22 +08:00
gloamxun aa072f58d8 Reserve outer tabcolsep margins around tables 2026-10-26 20:29:51 +08:00
gloamxun 20d23ce68d Record the round-150 handoff 2026-10-26 04:54:57 +08:00
gloamxun b191f7d66c Record the remaining compatibility gaps 2026-10-26 04:52:57 +08:00
gloamxun 20813a6607 Ignore strut commands in running text 2026-10-26 04:52:34 +08:00
gloamxun 22f95c1536 Print character commands by codepoint 2026-10-26 04:50:54 +08:00
gloamxun 2476c1893f Keep leftline arguments flush left 2026-10-26 04:49:10 +08:00
gloamxun 3d33ee9dc3 Flush rightline arguments to the right margin 2026-10-26 04:47:29 +08:00
gloamxun 9aa7198aed Centre centerline arguments 2026-10-26 04:45:58 +08:00
gloamxun f11561f15f Keep raggedright blocks unjustified 2026-10-26 04:44:21 +08:00
gloamxun 337f1f6de6 Centre blocks after a centering declaration 2026-10-26 04:41:31 +08:00
gloamxun 3d1ace51ae Print registers as roman numerals 2026-10-26 04:39:55 +08:00
gloamxun ca433d256d Drop break hints and discretionary hyphens 2026-10-26 04:38:04 +08:00
gloamxun 6c771e0820 Reuse savebox content through usebox 2026-10-26 04:35:42 +08:00
gloamxun c57de1e03c Reserve the named TeX spaces in text 2026-10-26 04:32:40 +08:00
gloamxun 1e8b2367ca Space text with quad and punctuation commands 2026-10-26 04:30:22 +08:00
gloamxun c290b6f38d Reserve hspace width in running text 2026-10-26 04:28:03 +08:00
gloamxun 090f389589 Reject test servers that exit after a port race 2026-10-26 04:26:17 +08:00
gloamxun 313ea366d6 Expand more text symbol commands 2026-10-26 04:21:51 +08:00
gloamxun 55d34dc259 Drop layout-only commands from paragraph text 2026-10-26 04:19:18 +08:00
gloamxun fb111806e2 Keep the text of mbox and makebox commands 2026-10-26 04:17:26 +08:00
gloamxun 0c8228eced Lay out ensuremath bodies as math 2026-10-26 04:14:38 +08:00
gloamxun 0340878909 Pad color boxes by fboxsep 2026-10-26 04:11:42 +08:00
gloamxun 8e274a252d Separate table columns by twice tabcolsep 2026-10-26 04:09:57 +08:00
gloamxun d89b71bfbc Measure table cells with Computer Modern metrics 2026-10-26 04:07:29 +08:00
gloamxun 39f02b83c0 Cover a report-class document and restore a macro test 2026-10-26 04:00:39 +08:00
gloamxun ba05af11f2 Number report and book chapters above sections 2026-10-26 03:58:43 +08:00
gloamxun e6a12fae9a Treat tildes as spaces outside URLs 2026-10-26 03:54:15 +08:00
gloamxun 994c360ec0 Draw fbox frames without a background 2026-10-26 03:51:28 +08:00
gloamxun 3d01fbe589 Cover report and geometry documents in the compatibility corpus 2026-10-26 03:47:37 +08:00
gloamxun 90cf2236ee Space booktabs rows with addlinespace 2026-10-26 03:43:29 +08:00
gloamxun 09b6c2b810 Exercise a warning-free article and close inline table ends 2026-10-26 03:41:21 +08:00
gloamxun d362d189ac Define character commands with chardef 2026-10-26 03:38:50 +08:00
gloamxun e81c82cf61 Invert conditionals with unless 2026-10-26 03:36:11 +08:00
gloamxun 9873c84416 Compare characters and parity in conditionals 2026-10-26 03:34:31 +08:00
gloamxun 3156d1488a Compare token categories in ifcat 2026-10-26 03:32:50 +08:00
gloamxun d1d6672503 Parse delimited macro arguments 2026-10-26 03:29:37 +08:00
gloamxun 269c633233 Frame link annotations in the SVG preview 2026-10-26 03:23:22 +08:00
gloamxun 2126ba8436 Chain zero-argument expandafter prefixes 2026-10-26 03:20:56 +08:00
gloamxun 77d76af4a7 Accept DeclareRobustCommand and honour providecommand semantics 2026-10-26 03:18:48 +08:00
gloamxun 7dbcea2319 Parenthesise glue expressions and keep register components 2026-10-26 03:16:20 +08:00
gloamxun fe1a001e62 Widen numbered registers to 256 slots 2026-10-26 03:10:47 +08:00
gloamxun 2018e5f8b8 Paint framed colorbox backgrounds 2026-10-26 03:08:37 +08:00
gloamxun d88e74cd29 Paint colorbox backgrounds 2026-10-26 03:05:07 +08:00
gloamxun eebe6deac5 Track scratch dimension and glue registers 2026-10-26 03:00:45 +08:00
gloamxun a25c3aace3 Evaluate scratch count registers 2026-10-26 02:58:53 +08:00
gloamxun e4720407a9 Evaluate glue expressions over skip registers 2026-10-26 02:56:23 +08:00
gloamxun d011806343 Discard gobbled arguments and test argument emptiness 2026-10-26 02:53:30 +08:00
gloamxun cb00e21127 Accept long global and protected definition prefixes 2026-10-26 02:51:35 +08:00
gloamxun c95cfa5967 Colour link annotation borders 2026-10-26 02:48:57 +08:00
gloamxun 352c44a9b1 Choose branches with @ifstar and @ifnextchar 2026-10-26 02:46:15 +08:00
gloamxun 7e3877df98 Track glue registers with newskip 2026-10-26 02:42:20 +08:00
gloamxun ea89bc1522 Colour href labels from hypersetup 2026-10-26 02:38:41 +08:00
gloamxun 8f429b892b Mix named colors with xcolor bang specs 2026-10-26 02:36:21 +08:00
gloamxun 69dc0a4863 Evaluate dimexpr dimension arithmetic 2026-10-26 02:34:21 +08:00
gloamxun 1ab2a29bfa Fill the page background with pagecolor 2026-10-26 02:31:50 +08:00
gloamxun 4cb456743a Honour definecolor models in text colors 2026-10-26 02:28:05 +08:00
gloamxun a888421f0e Colour the rest of a paragraph after a color switch 2026-10-26 02:21:13 +08:00
gloamxun 0d8125f854 Track dimension registers alongside integer counts 2026-10-26 02:18:30 +08:00
gloamxun 99eb24c153 Evaluate numexpr arithmetic in the body 2026-10-26 02:16:37 +08:00
gloamxun 676a6976f8 Expand the common LaTeX internal commands 2026-10-26 02:14:42 +08:00
gloamxun ded738d445 Choose ifcase branches and fall back to else 2026-10-26 02:08:16 +08:00
gloamxun 4352922240 Protect tokens from expansion with noexpand 2026-10-26 02:06:23 +08:00
gloamxun c74d604c40 Compare integers and token meanings in conditionals 2026-10-26 02:01:32 +08:00
gloamxun a0f4a35c94 Track integer count registers 2026-10-26 01:58:56 +08:00
gloamxun 206591c725 Test declared macros with ifdefined 2026-10-26 01:56:31 +08:00
gloamxun fa93b198bf Expand the macro after an expandafter prefix once 2026-10-26 01:52:46 +08:00
gloamxun 863f3e1b80 Expand edef bodies and csname sequences at definition time 2026-10-26 01:44:43 +08:00
gloamxun 028137a9ad Parse phantom bodies as braced groups 2026-10-26 01:41:27 +08:00
gloamxun 9ad404acee Paint textcolor runs in named colours 2026-10-26 01:41:00 +08:00
gloamxun f98964f6b6 Expand multirow cells to their text 2026-10-26 01:33:51 +08:00
gloamxun 20a2b1fa1f Fill tabularx X columns from the target width 2026-10-26 01:29:52 +08:00
gloamxun 7ba66392ea Set operator names upright and declare new ones 2026-10-26 01:24:46 +08:00
gloamxun a4c4864d2b Nest PDF bookmarks by heading level 2026-10-26 01:20:41 +08:00
gloamxun 5f98c199a5 Write PDF bookmarks for section headings 2026-10-26 01:17:42 +08:00
gloamxun 863e7c1a81 Write PDF metadata from hypersetup 2026-10-26 01:15:02 +08:00
gloamxun 8686b9a35e Stack substack rows with TeX inter-row gaps 2026-10-26 01:12:00 +08:00
gloamxun 0b611b6b1e Resolve pageref through a probe layout 2026-10-26 01:07:55 +08:00
gloamxun ab5e857705 Build genfrac fractions with explicit delimiters 2026-10-26 01:03:31 +08:00
gloamxun d237e0cc9b Keep integral scripts beside the operator 2026-10-26 01:01:11 +08:00
gloamxun 569160f805 Check stacked limits against pdfLaTeX 2026-10-26 00:59:19 +08:00
gloamxun 52a74755f7 Check matrix and cases positions against pdfLaTeX 2026-10-26 00:53:40 +08:00
gloamxun e926bc9eb3 Honour explicit limits and nolimits on operators 2026-10-26 00:48:52 +08:00
gloamxun 29d363d47a Set multline rows flush to the margins 2026-10-26 00:46:22 +08:00
gloamxun 4edc951958 Support split bodies and alignat rows 2026-10-26 00:42:08 +08:00
gloamxun 59b6ca571b Lay out matrix and array environments as grids 2026-10-26 00:39:28 +08:00
gloamxun 971190df26 Report diagnostics and lay out cases environments 2026-10-26 00:35:08 +08:00
gloamxun a28e8926c7 Report unsupported environments and leaked commands 2026-10-26 00:31:43 +08:00
gloamxun c9a074b1fe Audit the M3-M7 stage and record residual gaps 2026-10-25 02:37:42 +08:00
gloamxun 7350fb7cd4 Repeat star column groups in table templates 2026-10-25 02:33:53 +08:00
gloamxun 87d5f55be2 Respect combined float placement options and bold description terms 2026-10-25 02:32:11 +08:00
gloamxun 6d0794ef3a Paint vertical rules from table column separators 2026-10-25 02:29:23 +08:00
gloamxun 8bd725e9ff Accept table position options and row separator gaps 2026-10-25 02:26:19 +08:00
gloamxun 18c0288db0 Transform MakeUppercase and MakeLowercase arguments 2026-10-25 02:23:57 +08:00
gloamxun 81e6a2befc Accept displaymath and math environments 2026-10-25 02:21:47 +08:00
gloamxun 4f59f6e98c Resume enumerate numbering from setcounter lines 2026-10-25 02:19:25 +08:00
gloamxun 0200967982 Expand TeX letter and symbol commands to Unicode 2026-10-25 02:17:14 +08:00
gloamxun 0b2265580f Raise and lower superscript and subscript runs 2026-10-25 02:14:51 +08:00
gloamxun 9dea19d5aa Compose Unicode letters from TeX accent commands 2026-10-25 02:11:32 +08:00
gloamxun bb26825e12 Lay minipage bodies out at their declared width 2026-10-25 02:06:12 +08:00
gloamxun 54efd62e40 Declare new counters and add to counter values 2026-10-25 02:03:37 +08:00
gloamxun 51e039f9bf Use the proof optional argument as its heading 2026-10-25 02:01:18 +08:00
gloamxun 697d84aab3 Cover FIFO eviction in the flat route-D caches 2026-10-25 01:58:23 +08:00
gloamxun 0a91f7e9db Exercise PDF cache concurrency and retry test requests 2026-10-25 01:56:37 +08:00
gloamxun f1e0b75499 Parse center and quotation bodies as nested blocks 2026-10-25 01:54:48 +08:00
gloamxun 25eef7097b Capture longtable sources through the tabular path 2026-10-25 01:50:28 +08:00
gloamxun d2497dd079 Place standalone rule paragraphs as rule boxes 2026-10-25 01:48:17 +08:00
gloamxun 4d71094fba Exercise the flat preview cache under concurrent requests 2026-10-25 01:46:17 +08:00
gloamxun a11a9ec641 Cover the engine parameter matrix over the environment default 2026-10-25 01:44:26 +08:00
gloamxun df977704c5 Keep verse line breaks as separate lines 2026-10-25 01:42:20 +08:00
gloamxun 1b147235b0 Offset printed page numbers with setcounter page 2026-10-25 01:40:00 +08:00
gloamxun ae61d11859 Lead table-of-contents entries with dots 2026-10-25 01:37:38 +08:00
gloamxun 7dd94d7fbe Indent quotation blocks on both margins 2026-10-25 01:35:02 +08:00
gloamxun a9ab265be4 Hang list continuation lines at the text indent 2026-10-25 01:32:05 +08:00
gloamxun 16b9ea4a79 Follow article list skips at every nesting level 2026-10-25 01:28:02 +08:00
gloamxun 70ef8f3c8c Space list items with topsep and itemsep 2026-10-25 01:25:21 +08:00
gloamxun fa99aaccfa Append page numbers to float lists 2026-10-25 01:21:49 +08:00
gloamxun 60281dc9ca Show page numbers in the table of contents 2026-10-25 01:19:10 +08:00
gloamxun aaa1ed8213 Map Type1 glyphs through their requested Unicode 2026-10-25 01:14:54 +08:00
gloamxun a969b5acdf Retry test server startup on occupied ports 2026-10-25 01:11:31 +08:00
gloamxun 8bf56bac09 Handle citation notes and bibliography commands 2026-10-25 01:11:31 +08:00
gloamxun 22c81cbb88 Use short captions in float lists 2026-10-25 01:07:14 +08:00
gloamxun 0ea4bd65e8 Expand common text symbol commands 2026-10-25 01:02:50 +08:00
gloamxun 0b4c2ec394 Honour noindent at the start of a paragraph 2026-10-25 01:01:07 +08:00
gloamxun eaa0122901 Limit thispagestyle empty to the first page 2026-10-25 00:58:21 +08:00
gloamxun ed7c30c6a1 Print centered page numbers under the text block 2026-10-25 00:56:22 +08:00
gloamxun 7231b66fdc Note the ohm-sign extraction alias 2026-10-25 00:53:30 +08:00
gloamxun 7e006cea86 Cover Greek text through the Liberation fallback 2026-10-25 00:53:17 +08:00
gloamxun 067917eae5 Add to named lengths with addtolength 2026-10-25 00:50:43 +08:00
gloamxun 0327e64d24 Resolve setlength through named length registers 2026-10-25 00:49:11 +08:00
gloamxun de00eadcad Keep placeholders for missing or undecodable images 2026-10-25 00:46:00 +08:00
gloamxun 482217c017 Support optional first arguments in newcommand macros 2026-10-25 00:44:01 +08:00
gloamxun 3723036710 Run package document hooks and strip makeat 2026-10-25 00:41:24 +08:00
gloamxun e3e230042a Answer flat route-D errors with JSON messages 2026-10-25 00:39:04 +08:00
gloamxun 9cd8721846 Start theorem counters from setcounter values 2026-10-25 00:36:53 +08:00
gloamxun d379d941bb Start equation numbering from setcounter values 2026-10-25 00:34:19 +08:00
gloamxun 2640884721 Offset section and float counters with setcounter 2026-10-25 00:32:16 +08:00
gloamxun ea0468783e Use heading short titles in the table of contents 2026-10-25 00:27:51 +08:00
gloamxun 19c492b11d Open float lists with configurable headings 2026-10-25 00:25:50 +08:00
gloamxun 0dbca4305b Open the tables of contents and bibliography with headings 2026-10-25 00:23:41 +08:00
gloamxun f23a841e79 Rename float and abstract labels with renewcommand 2026-10-25 00:21:11 +08:00
gloamxun fd6217b3c7 Scale tabular rows with arraystretch
\renewcommand{\arraystretch}{factor} (or \def\arraystretch) multiplies
the tabular line height and recomputes the table height from the new row
heights, so classes that loosen table leading render like LaTeX.
2026-10-25 00:17:44 +08:00
gloamxun a923ec0970 Apply tabcolsep to tabular columns
The captured tabular path passed \tabcolsep as scaled points to a
constructor that expects points, so the default gap was huge. Pass the
6pt default properly and let \tabcolsep (or \setlength{\tabcolsep})
override the per-boundary glue, keeping the table width in step.
2026-10-25 00:16:09 +08:00
gloamxun 1a74ece3ba Accept baselinestretch as the linespread factor
LaTeX classes often set leading through \renewcommand{\baselinestretch}
instead of \linespread. Both forms, including \def\baselinestretch, now
feed the same factor and scale the class baseline.
2026-10-25 00:11:49 +08:00
gloamxun e43d5fcaaa Scale the class baseline with linespread
\linespread{factor} in the preamble multiplies the article class
\baselineskip (12/13.6/14.5pt by base size), clamped to a sane range, so
class files that loosen leading render with the wider interline glue.
2026-10-25 00:09:43 +08:00
gloamxun 9195d090de Merge passed package and class options
Preamble \PassOptionsToPackage and \PassOptionsToClass declarations are
collected and merged into the next \usepackage or \documentclass request,
so the shared option lists in article-class projects reach the local
class and package option protocol.
2026-10-25 00:07:39 +08:00
gloamxun 6aa9d70a49 Keep inline math inside styled runs 2026-10-25 00:04:54 +08:00
gloamxun c6860b7b4a Fall back per glyph outside the Type1 encodings 2026-10-25 00:03:19 +08:00
gloamxun 9ae86d9c86 Retry transient test server requests 2026-10-24 23:59:20 +08:00
gloamxun 5b160f9780 Render inline verb spans in the mono face 2026-10-24 23:59:20 +08:00
gloamxun 2868a8f0d3 Draw cline partial rules in alignment tables 2026-10-24 23:54:38 +08:00
gloamxun 78ffd054d4 Span multicolumn cells in LaTeX tables 2026-10-24 23:51:28 +08:00
gloamxun 04446e673f Inline input files inside project classes and packages 2026-10-24 23:47:57 +08:00
gloamxun cca108dc15 Memoise the flat route-D render endpoints 2026-10-24 23:45:28 +08:00
gloamxun 476be05163 Place standalone graphics as in-text floats 2026-10-24 23:42:14 +08:00
gloamxun a9614ccee2 Honour vspace as paragraph glue 2026-10-24 23:39:53 +08:00
gloamxun 32ca78bff5 Honour secnumdepth and tocdepth counters 2026-10-24 23:38:08 +08:00
gloamxun 9aacb91184 Resolve graphics through graphicspath directories 2026-10-24 23:35:14 +08:00
gloamxun 46f86c771e Size included graphics from their TeX options 2026-10-24 23:32:19 +08:00
GloamXun 0f8aff7290 Embed project images in route-D previews and PDFs 2026-10-24 23:29:15 +08:00
gloamxun ae69eba64d Paint inline size changes at their own size 2026-10-24 23:22:29 +08:00
gloamxun 00f95fdd09 Execute option declarations in local packages 2026-10-24 23:18:28 +08:00
gloamxun 9b44d68440 Expand today and default the title date 2026-10-24 23:16:07 +08:00
gloamxun fe9e93f796 Inline local base classes from LoadClass 2026-10-24 23:14:01 +08:00
gloamxun 4b0e4eba0c Cache route-D project PDF exports 2026-10-24 23:10:09 +08:00
gloamxun 6d5a3eb686 Run local class option declarations 2026-10-24 23:07:51 +08:00
gloamxun 11cfa44c2b Test link annotations in route-D PDFs 2026-10-24 23:05:05 +08:00
gloamxun 91a75820a4 Default to route-D with TEXRRA_ENGINE 2026-10-24 23:03:34 +08:00
gloamxun b30bafca2b Annotate href links in route-D PDFs 2026-10-24 23:00:41 +08:00
gloamxun fbb316baa9 Honour item labels in list environments 2026-10-24 22:54:16 +08:00
gloamxun 4ac3add870 Number paragraph and subparagraph headings 2026-10-24 22:51:14 +08:00
gloamxun 0651e15111 Cache route-D project previews by expanded source 2026-10-24 22:47:19 +08:00
gloamxun 874a327dca Expand href text and url typewriter text 2026-10-24 22:42:17 +08:00
gloamxun 8610a6c016 Preserve verbatim environments as monospaced lines 2026-10-24 22:39:43 +08:00
gloamxun 8955babea8 List figures and tables from their numbered captions 2026-10-24 22:37:18 +08:00
gloamxun b2f5b67b07 Expand tableofcontents into numbered heading lines 2026-10-24 22:35:19 +08:00
gloamxun f48b10340a Inline required local packages recursively 2026-10-24 22:32:41 +08:00
gloamxun 64325d4b87 Inline local class files in project previews 2026-10-24 22:30:23 +08:00
gloamxun a7f3680a13 Inline local style packages in project previews 2026-10-24 22:27:30 +08:00
gloamxun 491d4e528a Honour conditional assignments in the body 2026-10-24 22:23:54 +08:00
gloamxun 6c81a07766 Execute newif conditionals in the document body 2026-10-24 22:21:47 +08:00
gloamxun e99fab2086 Expand newenvironment definitions in the preamble 2026-10-24 22:15:51 +08:00
gloamxun 568442a75b Execute def and let definitions from the preamble 2026-10-24 22:12:24 +08:00
gloamxun 6a4483cf4d Expand input files in project PDF exports 2026-10-24 22:10:08 +08:00
gloamxun a5da5c9521 Execute newcommand macros from the preamble 2026-10-24 22:07:04 +08:00
gloamxun e008741aa5 Lay out inline math in paragraphs 2026-10-24 21:13:06 +08:00
gloamxun aae046a2f0 Place table captions above their tabular and footnote thanks notes 2026-10-24 21:08:04 +08:00
gloamxun ac1bf660af Nest list environments with depth-aware indentation 2026-10-24 21:04:21 +08:00
gloamxun 4ca3302367 Define custom theorem environments with newtheorem
Parse \newtheorem{env}[shared]{Display},
\newtheorem{env}{Display}[within] and \newtheorem*{env}{Display}
from the preamble. Custom environments gain a bold heading with their
display name, share counters through the optional parent, and can scope
their numbers to the enclosing section; the starred form stays
unnumbered. Unrecognised files and cycles are unaffected.
2026-10-24 21:00:45 +08:00
gloamxun 9599436447 Expand input and include files in project previews
Project previews now expand \input{...} and \include{...} from the
project store (adding a .tex suffix when needed) before route-D parses
the source. Unknown paths and cycles leave the directive as literal
text.
2026-10-24 20:56:54 +08:00
gloamxun 67eb719cbd Number theorem-like environments and resolve their labels 2026-10-24 20:53:43 +08:00
gloamxun a9fbc9b850 Carry table environments as floats with their tabular body 2026-10-24 20:48:29 +08:00
gloamxun 5c04fa83ab Carry figure environments as floats 2026-10-24 20:44:37 +08:00
gloamxun ea06e299d6 Resolve citations from a thebibliography block 2026-10-24 20:38:44 +08:00
gloamxun d4efee043c Page-set footnotes as numbered insertions 2026-10-24 20:35:48 +08:00
gloamxun 6176edccc4 Number appendix sections with letters 2026-10-24 20:30:48 +08:00
gloamxun d982e9266c Resolve section labels and references 2026-10-24 20:28:11 +08:00
gloamxun 17efd542f7 Join and authors and drop thanks notes 2026-10-24 20:25:46 +08:00
gloamxun b947f476da Expand the abstract environment 2026-10-24 20:24:02 +08:00
gloamxun 5ff94d8f92 Number sectioning headings with article counters 2026-10-24 20:22:31 +08:00
gloamxun 569bec31b6 Expand maketitle into the article title block 2026-10-24 20:17:55 +08:00
gloamxun 925c916ea5 Align centered and flushed blocks within the measure 2026-10-24 20:15:31 +08:00
gloamxun 2783dfb284 Apply geometry package margins to the page 2026-10-24 20:11:27 +08:00
gloamxun 6ae609b60e Honour textwidth and setlength as the paragraph measure 2026-10-24 20:09:17 +08:00
gloamxun c494ad04ae Read documentclass size options as the base font size 2026-10-24 19:47:45 +08:00
gloamxun 9876895a84 Scale paragraphs by their declared base font size 2026-10-24 13:04:19 +08:00
gloamxun aa4d86d735 Distinguish slanted from italic and add italic typewriter
Add cmsl10/cmbxsl10/cmitt10 faces so \slshape and \textsl no longer reuse the italic cmti10 and \ttfamily\itshape reaches cmitt10. The NFSS state tracks italic, slanted and small caps separately, with last-shape-wins semantics for \em and the shape commands.
2026-10-24 12:58:41 +08:00
gloamxun 6df38ced25 Scope NFSS declarations to the rest of their group
A bare \bfseries or \em in a paragraph now switches the face from that point to the end of the enclosing group, instead of being emitted as literal text. Inline declarations recurse into the remaining body so nested groups keep their own scope.
2026-10-24 12:55:13 +08:00
gloamxun e303f7852f Select real Computer Modern small caps
Add the cmcsc10 face for \scshape and \textsc, including its Type1 outline, and compose the sc shape with the surrounding family and series. Bold small caps substitute cmbx10 and a later shape command wins, matching NFSS.
2026-10-24 12:52:15 +08:00
gloamxun 9140990a7d Add sans-serif bold and italic faces
Map \sffamily with \bfseries or \itshape onto the bundled cmssbx10 and cmssi10 metrics, with their Type1 outlines embedded alongside the other Computer Modern faces. Bold italic sans substitutes cmssbx10, matching the OT1 fallback in TeX.
2026-10-24 12:49:30 +08:00
gloamxun 03925e3116 Scan TeX math skips and correct math-unit spacing 2026-10-24 12:43:01 +08:00
gloamxun cce656a407 Lay out align and gather displays row by row 2026-10-24 12:39:02 +08:00
texrra 8c42f2de2f Add Fraktur letters, infix fractions and middle delimiters
- bundle eufm10 (TFM + Type1), add the MathFraktur face and map \mathfrak
  onto it, including PDF embedding and width lookup;
- parse TeX's infix fractions (\over, \atop, \choose, \brace,
  \brack, \overwithdelims, \atopwithdelims): the rest of the current
  row becomes the denominator, ar records whether a rule is drawn, and the
  painter no longer emits parentheses (a \frac painter bug) and only draws
  the bar for \over forms;
- add MathAtom::Middle, size top-level middle delimiters with the enclosing
  \left/\right group through the CMEX size classes, and paint
  SizedDelimiter at its selected size instead of the base glyph;
- skip the parser's '\u{0}' math spaces before \big, \middle,
  \left and the withdelims delimiters, so \big ( parses like \big(.

560 workspace tests (381 route-D unit).
2026-10-24 12:28:33 +08:00
gloamxun cb40cc4634 Draw mathbb letters from msbm10 2026-10-24 12:14:54 +08:00
gloamxun e229809581 Draw mathcal letters from cmsy10 2026-10-24 03:49:55 +08:00
gloamxun 66ceabad0e Draw big operators with cmex10 outlines 2026-10-24 03:46:50 +08:00
gloamxun 6446de6b6b Embed math symbols as Computer Modern Type1 outlines 2026-10-24 03:42:45 +08:00
gloamxun a07d93510f Map math alphabets onto Computer Modern Type1 faces 2026-10-24 03:38:53 +08:00
gloamxun a95cf8092e Embed math italic letters as Computer Modern Type1 outlines 2026-10-24 03:35:33 +08:00
gloamxun f7849f39c2 Embed every Computer Modern face as Type1 outlines 2026-10-24 03:30:12 +08:00
gloamxun 5f5fc393a4 Embed Computer Modern Type1 outlines in route-D PDFs 2026-10-24 03:28:10 +08:00
gloamxun 6eef2f7a54 Record the Type1 parser in the docs 2026-10-24 03:24:53 +08:00
gloamxun 5b5fdab8a6 Parse Computer Modern Type1 programs for PDF embedding 2026-10-24 03:24:32 +08:00
gloamxun 36f2aa12d7 Keep styled runs across incremental paragraph edits 2026-10-24 02:18:21 +08:00
gloamxun 4cf64a4d55 Compose nested inline faces relative to the surrounding run 2026-10-24 02:15:08 +08:00
gloamxun 0e8999671b Parse declaration groups in inline styled text 2026-10-24 02:12:29 +08:00
gloamxun 53fabe95db Paint inline NFSS runs with their own faces 2026-10-24 02:09:56 +08:00
gloamxun 67898d6a8a Support NFSS command forms and legacy declarations 2026-10-24 02:06:44 +08:00
gloamxun df43cade62 Select built-in faces from NFSS declarations 2026-10-24 02:04:14 +08:00
gloamxun f6726439ed Support tag and notag on numbered equations 2026-10-24 02:00:47 +08:00
gloamxun bb897411d0 Number equation environments in route-D 2026-10-24 01:57:18 +08:00
gloamxun 3cbfdabe03 Space math atoms with the full TeX class table 2026-10-24 01:51:10 +08:00
gloamxun f7e89c78a2 Select CMEX delimiter sizes for left and right 2026-10-24 01:47:42 +08:00
gloamxun 4c2aefd490 Use CMEX size variants for big math delimiters 2026-10-24 01:42:49 +08:00
gloamxun 03afc828f3 Use cmsy10 symbol metrics in route-D formulas 2026-10-24 01:38:15 +08:00
gloamxun 8f675bcabd Use Computer Modern math metrics for route-D formulas 2026-10-24 01:31:51 +08:00
gloamxun c9ad1e209a Split wide display formulas into lines 2026-10-24 01:26:29 +08:00
gloamxun 95e677b5c7 Map LaTeX tabular sources onto route-D halign 2026-10-24 01:22:36 +08:00
gloamxun 20011eadd3 Repeat longtable heads on continuation pages 2026-10-24 01:14:38 +08:00
gloamxun 8c3e410ffc Insert noalign glue between alignment rows 2026-10-24 01:10:49 +08:00
gloamxun 3681fd95db Honour @ column expressions in alignment templates 2026-10-24 01:07:48 +08:00
gloamxun c3e75bd244 Draw booktabs rules with their own weights and spans 2026-10-24 01:03:53 +08:00
gloamxun d0ffeea94b Honour explicit tabskip glue in alignments 2026-10-24 00:59:33 +08:00
gloamxun d1b93ac9be Wrap p-column cells and keep wrapped rows splittable 2026-10-24 00:57:09 +08:00
gloamxun 4153657d0a Continue long alignments across pages 2026-10-24 00:51:48 +08:00
gloamxun f980ed7f56 Audit the G1 milestones and refresh the plan status 2026-10-24 00:42:22 +08:00
gloamxun a93200cbfb Support classed marks in the output routine 2026-10-24 00:39:59 +08:00
gloamxun 91171f2a90 Carry output-routine marks onto the following page 2026-10-24 00:37:46 +08:00
gloamxun d4906a3cc5 Apply assigned insertion skip to later pages 2026-10-24 00:32:52 +08:00
gloamxun de84ffc979 Retarget later pages after a vsize assignment 2026-10-24 00:28:29 +08:00
gloamxun 0805f3c932 Reserve insertion class skip in the paged builder 2026-10-24 00:23:55 +08:00
gloamxun 1dc3e95a04 Run the output routine after each paged page 2026-10-24 00:20:32 +08:00
gloamxun 23956a012b Expose hsize and the page box width to the output routine 2026-10-24 00:14:55 +08:00
gloamxun 49079f7e70 Record that P1 registers are complete 2026-10-24 00:08:25 +08:00
gloamxun c3bb8af8a9 Verify narrow-measure pretolerance against pdfLaTeX 2026-10-24 00:07:26 +08:00
gloamxun 01ed1b7c21 Report page badness and held-over insertions to the output routine 2026-10-24 00:02:46 +08:00
gloamxun bf31936146 Prefer the later equal-cost page break 2026-10-23 23:58:28 +08:00
gloamxun 66b2ccf380 Rebuild paged documents that defer bottom floats 2026-10-23 23:51:18 +08:00
gloamxun 4dd28b3aa7 Defer bottom floats like TeX page building 2026-10-23 23:48:28 +08:00
gloamxun 17638996a1 Defer bottom floats inside the page builder 2026-10-23 23:43:32 +08:00
gloamxun fd9790cf28 Cover bottom float page placement with pdfLaTeX 2026-10-23 23:39:24 +08:00
gloamxun a09b1d1d36 Clamp held-over insertion depth with splitmaxdepth 2026-10-23 23:35:20 +08:00
gloamxun 0f4c1f85ae Report paragraph depth to the page builder 2026-10-23 23:31:47 +08:00
gloamxun bd28917f05 Run TeX arithmetic on output registers 2026-10-23 23:21:55 +08:00
gloamxun db1cc98338 Place top floats on the page they appear on 2026-10-23 23:15:56 +08:00
gloamxun a78e0c1d0d Compare footnote insertions with pdfLaTeX page breaks 2026-10-23 15:09:18 +08:00
gloamxun 6b3145fd09 Route route-D page breaking through the paged builder 2026-10-23 15:02:52 +08:00
gloamxun 08a312be82 Carry plus and minus on inter-paragraph skip glue 2026-10-23 14:53:00 +08:00
gloamxun 6f1310a876 Document the narrow-measure tolerance approximation 2026-10-23 14:45:04 +08:00
gloamxun 2d73486dd1 Cover tolerance-10000 line breaking with pdfLaTeX 2026-10-23 14:43:57 +08:00
gloamxun 2b2ccd511c Break pages only at legal glue points 2026-10-23 14:38:35 +08:00
gloamxun 247cbf2b9e Start route-D pages on newpage breaks 2026-10-23 14:32:27 +08:00
gloamxun 4111080422 Ship the page after maxdeadcycles 2026-10-23 14:26:58 +08:00
gloamxun 8007fd1b6c Report TeX outputpenalty for glue breaks 2026-10-23 14:22:34 +08:00
gloamxun 94559ee431 Carry TeX plus and minus on paragraph skips 2026-10-23 14:18:13 +08:00
gloamxun 0102a20120 Support explicit vertical skips between paragraphs 2026-10-23 14:15:17 +08:00
gloamxun d596ef2a95 Apply page offsets to route-D preview pages 2026-10-23 14:11:05 +08:00
gloamxun aea6c289ec Read sfcode assignments from route-D sources 2026-10-23 14:07:37 +08:00
gloamxun de35d1bcae Read demerit registers from route-D sources 2026-10-23 14:05:25 +08:00
gloamxun e823a1f415 Read page skip registers from route-D sources 2026-10-23 14:03:39 +08:00
gloamxun bd462448d5 Read parfillskip and interline glue from route-D sources 2026-10-23 14:01:27 +08:00
gloamxun dc68e76cd3 Read parshape measures from route-D sources 2026-10-23 13:58:15 +08:00
gloamxun f86b507615 Read hyphenation exceptions from route-D sources 2026-10-23 13:54:58 +08:00
gloamxun e00e0038c1 Cover hyphenated breaks and hyphen demerits with pdfLaTeX 2026-10-23 13:52:04 +08:00
gloamxun a6397fcfef Honour TeX looseness when an alternative line count exists 2026-10-23 13:46:32 +08:00
gloamxun 96cd98f833 Read hang indent, spacing and tolerance registers from route-D sources 2026-10-23 13:34:13 +08:00
gloamxun 53436f8177 Correct the route-D server test count 2026-10-23 13:28:51 +08:00
gloamxun 4f4171a6d1 Read paragraph registers from route-D sources and measure with TFM advances 2026-10-23 13:28:43 +08:00
gloamxun be23fe9686 Expose the page box height and depth to the output routine 2026-10-23 13:24:14 +08:00
gloamxun 70b360e50e Keep output register assignments across pages 2026-10-23 13:20:56 +08:00
gloamxun 7a42ddc1bf Expose prevgraf to the output routine 2026-10-23 13:18:21 +08:00
gloamxun d63db8d12d Support explicit hfil and hfill glue orders 2026-10-23 13:15:40 +08:00
gloamxun 3df21201c2 Verify parindent, parshape and skips against pdfLaTeX 2026-10-23 13:10:40 +08:00
gloamxun 97b72ac5d9 Honour textheight geometry and widen the page oracle 2026-10-23 13:07:11 +08:00
gloamxun c6ebbea58d Let the output routine retarget later pages with vsize 2026-10-23 13:02:47 +08:00
gloamxun 3b99f93ab8 Read vsize from route-D sources as the page goal 2026-10-23 12:56:47 +08:00
gloamxun 59e77f4721 Allow the output routine to assign page registers 2026-10-23 12:53:40 +08:00
gloamxun 2a3393a61e Count dead cycles across output routine pages 2026-10-23 12:48:19 +08:00
gloamxun 66dfb10b60 Ship float-heavy pages without body material 2026-10-23 12:45:53 +08:00
gloamxun 594a57e414 Make server test startup failures diagnosable 2026-10-23 12:42:22 +08:00
gloamxun 140e1b4c50 Cover final and double hyphen demerits 2026-10-23 12:36:36 +08:00
gloamxun 54a8488fa2 Limit paged floats by topnumber and bottomnumber 2026-10-23 12:32:02 +08:00
gloamxun c2ba59906c Read insertion class registers in the output routine 2026-10-23 12:28:09 +08:00
gloamxun 72f5436318 Replay paged edits with later insertions and keep zero parskip breakpoints 2026-10-23 12:25:01 +08:00
gloamxun e632db02cf Start held-over insertions with splittopskip 2026-10-23 12:15:27 +08:00
gloamxun c54a56ad36 Reduce page goal by reserved insertion space 2026-10-23 04:25:24 +08:00
gloamxun a4388942f0 Expose per-order page stretch to the output routine 2026-10-23 04:22:27 +08:00
gloamxun 52e3e0647c Set pages with TeX glue orders 2026-10-23 04:18:14 +08:00
gloamxun 00c23a3511 Set vertical glue for ragged and flushed pages 2026-10-23 04:13:12 +08:00
gloamxun 448152cea4 Support ragged-right paragraphs with an infinite rightskip 2026-10-23 04:08:32 +08:00
gloamxun f488dd3b6c Flow in-text floats through the paged builder 2026-10-23 04:04:03 +08:00
gloamxun 14ca3b91d9 Place bottom floats through the paged builder 2026-10-23 03:57:44 +08:00
gloamxun 7b9d543e49 Honour declared paper size in route-D output 2026-10-23 03:53:32 +08:00
gloamxun 043ae7f072 Replay paged layouts from the edited page 2026-10-23 03:46:12 +08:00
gloamxun 6c3636c7c5 Compare route-D page breaks with pdfLaTeX 2026-10-23 03:40:08 +08:00
gloamxun c5b3493998 Draw paged top floats with their text float separation 2026-10-23 03:32:36 +08:00
gloamxun aa081e3dc6 Place top floats through the paged builder 2026-10-23 03:30:15 +08:00
gloamxun bc0d29ace4 Insert parskip between paragraphs in the paged builder 2026-10-23 03:26:53 +08:00
gloamxun ca36c94eb3 Expose page stretch and shrink to the output routine 2026-10-23 03:23:57 +08:00
gloamxun 62d3c4154e Expose page depth to the output routine 2026-10-23 03:21:36 +08:00
gloamxun c8805af755 Reject overfull lines outside the emergency pass 2026-10-23 03:17:25 +08:00
gloamxun 47ef33c536 Record the hyphen demerit fixture blocker 2026-10-23 03:13:47 +08:00
gloamxun 61cef7d16c Select output routine branches with ifcase 2026-10-23 03:10:55 +08:00
gloamxun 7964765605 Ship pages conditionally on parity in the output routine 2026-10-23 03:08:19 +08:00
gloamxun a2a2eafab5 Read output penalty and page number in the output routine 2026-10-23 03:04:58 +08:00
gloamxun 4bec90cf8c Interpret the output routine shipout and ifdim subset 2026-10-23 02:59:54 +08:00
gloamxun 6cf8221ba7 Lay out insertion classes through the page builder 2026-10-23 02:53:04 +08:00
gloamxun 6305f059ac Shrink overfull final lines and widen the oracle matrix 2026-10-23 02:45:11 +08:00
gloamxun bcd3b6fa66 Expand vertical units in the paged builder 2026-10-23 02:40:36 +08:00
gloamxun 4be0ff5787 Replace font glue with explicit spaceskip and xspaceskip 2026-10-23 02:38:12 +08:00
gloamxun 4acccaee86 Honour explicit sfcode assignments 2026-10-23 02:29:40 +08:00
gloamxun b5ec36ae2a Split insertions at the page break and hold over the tail 2026-10-23 02:26:56 +08:00
gloamxun b7b75fbff1 Split paragraphs at line boundaries across pages 2026-10-23 02:23:18 +08:00
gloamxun daf9f5c57e Expose TeX carried marks for page headers 2026-10-23 02:00:29 +08:00
gloamxun 8d319b3b0c Apply TeX page offsets in the route-D PDF endpoint 2026-10-23 01:57:48 +08:00
gloamxun 5db7acaff2 Shift the route-D page body by TeX page origin offsets 2026-10-23 01:55:28 +08:00
gloamxun fb33ac6327 Apply the insertion count multiplier to page space 2026-10-23 01:51:19 +08:00
gloamxun 169119a48d Cap page depth at Document max_depth 2026-10-23 01:48:21 +08:00
gloamxun 9599982b91 Feed simple documents through the TeX page builder 2026-10-23 01:45:45 +08:00
gloamxun d4a9c6b4fd Add a TeX page builder over vertical lists 2026-10-23 01:41:06 +08:00
gloamxun 49bd9b63e6 Model TeX interline glue and parskip 2026-10-23 01:36:26 +08:00
gloamxun 8cb09ea5a8 Support TeX looseness on paragraph final lines 2026-10-23 01:26:54 +08:00
gloamxun 295c934438 Apply TeX sentence spacing to interword glue 2026-10-23 01:26:04 +08:00
gloamxun bd109d03c5 Honour finite parfillskip on the last line 2026-10-23 01:22:16 +08:00
gloamxun 8993186005 Support hang indentation and parshape measures 2026-10-23 01:18:19 +08:00
gloamxun 24a96d1c7c Model TeX demerit registers and hyphenation exceptions 2026-10-23 01:12:52 +08:00
texrra 3725cca9d7 Model TeX tolerance and hyphen penalty registers 2026-10-23 01:05:28 +08:00
texrra 4fbc43f5ff Match TeX hyphenation and justification semantics 2026-10-23 01:00:45 +08:00
gloamxun ac134b3c4e Reproduce TeX paragraph breaking with tolerance passes and demerits
- replace the single-tolerance DP with pass 0 (pretolerance, no hyphenation),
  pass 1 (tolerance, hyphenation) and an optional emergency pass
- add emergencystretch to ParagraphStyle; the emergency pass only runs when it
  is positive, otherwise TeX's overfull fallback applies and each line fills to
  the first break at or past the measure
- compute badness and fitness classes like TeX and fold them with penalties
  into demerits, ignoring the trailing forced penalty on the final line
- keep forward order in the greedy fallback
- enable the 180pt pdfLaTeX oracle fixture and add an emergencystretch test
- give route-D extraction tests scaled body styles so fixed-cell
  ParagraphStyle defaults no longer mix raw units with TFM advances
- document the passes, oracle results and remaining P1 gaps
2026-10-23 00:50:57 +08:00
gloamxun 03aa1c5110 Record the P1 line-breaking experiment 2026-10-23 00:35:43 +08:00
gloamxun 9726f5f736 Add a pdfLaTeX oracle and clamp justification glue 2026-10-23 00:33:35 +08:00
gloamxun 1e2d4afd6b Plan the complete route-D program 2026-10-23 00:19:59 +08:00
gloamxun 4414f27438 Justify route-D lines and compare ink bands with pdfTeX 2026-10-22 19:45:31 +08:00
gloamxun 93330a85ef Start float pages at the top margin 2026-10-21 12:57:51 +08:00
gloamxun d2df1907be Keep in-text floats in the body flow 2026-10-21 12:55:42 +08:00
gloamxun 830e1f851b Reserve textfloatsep between floats and body text 2026-10-21 12:51:01 +08:00
gloamxun 1014713ec0 Reserve floatsep between stacked floats 2026-10-21 12:46:24 +08:00
gloamxun 521c87d952 Use per-face Computer Modern TFMs for paragraph layout 2026-10-21 12:23:08 +08:00
gloamxun 7cb5b42429 Preserve paragraph font faces across edits 2026-10-21 09:33:31 +08:00
gloamxun 763ae99e8e Compare route-D text extraction with pdfTeX 2026-10-21 09:31:18 +08:00
gloamxun c6a58dd646 Report matching PDF widths for accented glyphs 2026-10-21 09:25:46 +08:00
gloamxun 3d94e28dff Carry TFM glyph height and depth into paragraph boxes 2026-10-21 09:18:15 +08:00
gloamxun 8731ec2b9e Subset embedded fonts to the glyphs a document uses 2026-10-21 09:14:46 +08:00
gloamxun 06779fb8dd Support per-class insertion skip
InsertionClass gains skip, matching TeX skip registers for insertion classes. The page builder prefers that value over Document.insertion_skip for the class, in both full and incremental layout; regressions cover a skip that pushes an insertion to the next page and the edit path.
2026-10-21 09:01:12 +08:00
gloamxun 7385b8862a Honour TeX float number limits
Add top_number, bottom_number and total_number to Document with TeX defaults 2, 1 and 12. Top and bottom float branches, including the incremental edit path, refuse an extra float once its placement count or the total page count is reached, so the float moves to the next page.
2026-10-21 08:57:16 +08:00
gloamxun f2deac541e Reuse page prefixes for structural route-D edits
Extract Engine::relayout_from from Engine::edit so a caller can rebuild from any checkpoint with an unchanged unit prefix. Route-D project previews now use the first differing paragraph for both text and structural edits, keeping sealed pages before the change instead of always relaying out the whole document.
2026-10-21 08:53:17 +08:00
gloamxun 8cbd72663a Correct the documented route-D test count 2026-10-21 08:48:24 +08:00
gloamxun ceb31c4612 Replay multiple paragraph edits in route-D previews
Apply same-count paragraph edits sequentially from the earliest changed paragraph, reuse the earlier page checkpoints, and report the union of changed pages. Adds a multi-page regression.
2026-10-21 08:46:56 +08:00
gloamxun 506904bbdc Apply insertion class limits in incremental edits 2026-10-21 08:43:09 +08:00
gloamxun 68d2cef346 Compare two route-D pages with pdfTeX 2026-10-21 08:40:44 +08:00
gloamxun 180c05e425 Reserve skip before the first insertion class 2026-10-21 08:28:34 +08:00
gloamxun e052a0d0f3 Compress embedded font and ToUnicode streams
Route-D PDFs embedded full FontFile2 programs and ToUnicode CMaps uncompressed. Deflate both streams and declare /Filter /FlateDecode while keeping /Length1 as the uncompressed font length. The minimal route-D PDF now renders to 13.5 KB, and the pdfTeX raster comparison still matches.
2026-10-21 08:19:02 +08:00
gloamxun aeacf53518 Make the pdfTeX raster comparison actually run
pdftoppm --version exits non-zero, so the raster test silently skipped on every host. Probe pdftoppm with -v instead, lay out the route-D paragraph at the same scaled-point geometry the server uses, and compile the pdfTeX control page as Letter (612x792bp). The ink line count and left/right/bottom edges now match exactly.
2026-10-21 08:10:29 +08:00
gloamxun 5b4eadb88f Place late top floats on the current page when they fit 2026-10-21 01:33:14 +08:00
gloamxun 484375fa2b Support absolute insertion class height limits 2026-10-21 01:28:42 +08:00
gloamxun 12d8ae805b Keep insertions from multiple classes within the page height 2026-10-21 01:18:02 +08:00
gloamxun c3277531d3 Export project PDFs through route-D when selected 2026-10-21 01:15:09 +08:00
gloamxun 21cc743236 Document the route-D preview toggle 2026-10-21 01:12:12 +08:00
gloamxun 4166cb7e9b Update route-D test counts 2026-10-21 01:11:17 +08:00
gloamxun 95760e4a1c Turn TeX hyphen runs into en and em dashes 2026-10-21 01:08:22 +08:00
gloamxun ff97f386da Apply float-page fraction in incremental layout 2026-10-21 01:02:04 +08:00
gloamxun 93dd4e531b Apply bottom float fractions in incremental layout 2026-10-20 23:44:22 +08:00
gloamxun 48d10f901d Apply topfraction in incremental layout 2026-10-20 23:41:31 +08:00
gloamxun d81021d1a3 Honour topfraction for top floats 2026-10-20 23:37:47 +08:00
gloamxun 14a3775206 Honour bottomfraction when placing bottom floats 2026-10-20 23:33:21 +08:00
gloamxun c2dbf405ab Compare route-D raster geometry with pdfTeX 2026-10-20 23:20:28 +08:00
gloamxun ea69301804 Reuse route-D page checkpoints in project previews 2026-10-20 23:13:49 +08:00
gloamxun fe7fd68321 Let project previews opt into the route-D core 2026-10-20 23:09:32 +08:00
gloamxun a8e7499ce3 Honour per-class insertion page limits 2026-10-20 23:02:30 +08:00
gloamxun ff3fff343d Paint ligature boxes as their component letters 2026-10-20 22:59:31 +08:00
gloamxun 67915402a6 Use CMR10 advances for route-D paragraphs and PDF text 2026-10-20 22:55:38 +08:00
gloamxun 8251e35de2 Fix the route-D PDF text note 2026-10-20 22:28:34 +08:00
gloamxun 5c0ffd41ac Record the route-D PDF text extraction limitation 2026-10-20 22:27:48 +08:00
gloamxun 40ed26e339 Right-align route-D paragraphs and preview flushright blocks 2026-10-20 22:23:47 +08:00
gloamxun 6714591704 Use the minimal font tier for ASCII route-D PDFs 2026-10-20 22:21:10 +08:00
gloamxun 295093ae5a Embed only the font faces used by a route-D PDF 2026-10-20 22:15:53 +08:00
gloamxun 472f778e75 Center route-D paragraphs and preview center blocks 2026-10-20 22:12:39 +08:00
gloamxun 611e6fec96 Cover incremental edits of route-D list units 2026-10-20 22:08:30 +08:00
gloamxun a9e5f38ef7 Refresh route-D M1 and M7 status 2026-10-20 22:06:57 +08:00
gloamxun fcfb7ec764 Cover route-D list PDF export 2026-10-20 22:06:24 +08:00
gloamxun ccda740476 Indent quote blocks in the route-D preview 2026-10-20 22:04:50 +08:00
gloamxun 4772985ffe Render description lists in the route-D preview 2026-10-20 22:03:19 +08:00
gloamxun edf851438b Render enumerate lists in the route-D preview 2026-10-20 22:01:02 +08:00
gloamxun cea9ccddef Render itemize lists in the route-D preview 2026-10-20 21:59:17 +08:00
gloamxun 63593e7ff3 Render display math in the route-D preview 2026-10-20 21:57:12 +08:00
gloamxun 15880c884d Cover stable page hashes across route-D edits 2026-10-20 21:55:20 +08:00
gloamxun f0e5f14a8c Hash rendered page content instead of source metadata 2026-10-20 21:53:51 +08:00
gloamxun 2c4d968659 Map sections and emphasis in the route-D preview 2026-10-20 21:45:34 +08:00
gloamxun ec9ce3b765 Export route-D preview pages as PDF 2026-10-20 21:41:46 +08:00
gloamxun 8468c36daa Embed and paint a sans paragraph face 2026-10-20 21:37:37 +08:00
gloamxun 1633e441de Paint monospace paragraphs with the embedded mono face 2026-10-20 21:35:37 +08:00
gloamxun 6dd4f6bf83 Offset math scripts by the base italic correction 2026-10-20 21:34:09 +08:00
gloamxun 6a7e79fa03 Stack insertion classes from the page bottom 2026-10-20 21:32:15 +08:00
gloamxun 060405fca6 Apply CMR10 italic corrections at line ends 2026-10-20 21:27:39 +08:00
gloamxun 7e0090c7a5 Let custom output routines force a page break 2026-10-20 21:25:00 +08:00
gloamxun 77f05513ed Assert route-D edits reuse unchanged pages 2026-10-20 21:21:41 +08:00
gloamxun dbccedb579 Expose route-D page-hash diffs for paragraph edits 2026-10-20 21:18:57 +08:00
gloamxun fab9a473fc Render route-D preview pages at page size 2026-10-20 21:16:45 +08:00
gloamxun 875f8a7600 Expose route-D pages through a preview endpoint 2026-10-20 21:15:35 +08:00
gloamxun 12288b51ee Split oversized route-D insertions across pages 2026-10-20 21:07:26 +08:00
gloamxun ac63a3db92 Substitute CMR10 ligatures in route-D paragraphs 2026-10-20 21:04:24 +08:00
gloamxun 641fc1c14b Embed all route-D text faces with CID widths 2026-10-20 20:59:01 +08:00
gloamxun 5010e9ab10 Document route-D float page fractions 2026-10-20 20:54:26 +08:00
gloamxun 2431f3a479 Model float page fractions in route-D output 2026-10-20 20:54:06 +08:00
gloamxun 867bace1c9 Apply CMR10 kern pairs in route-D paragraphs 2026-10-20 20:52:54 +08:00
gloamxun a09398811f Embed a TrueType Roman font in route-D PDFs 2026-10-20 20:49:21 +08:00
gloamxun a703f2dcc0 Wire the TFM parser into the route-D core 2026-10-20 20:46:14 +08:00
gloamxun f909e8199c Parse cmr10 TFM metrics for route-D math 2026-10-20 20:44:52 +08:00
gloamxun 84e2e9cadb Update route-D test baseline 2026-10-20 19:37:44 +08:00
gloamxun 7b19a423a2 Record route-D open milestones 2026-10-20 19:36:43 +08:00
gloamxun afe59fc7b4 Center scaled math delimiters on the baseline 2026-10-20 19:36:20 +08:00
gloamxun 4fa6998f66 Record workspace verification baseline 2026-10-20 19:34:52 +08:00
gloamxun 40264a61dd Refresh route-D milestone status 2026-10-20 19:32:03 +08:00
gloamxun b9455e0438 Parse big-delimiter control sequences 2026-10-20 19:29:42 +08:00
gloamxun 72f7cfaf2a Grow left-right delimiters with tall bodies 2026-10-20 19:28:33 +08:00
gloamxun b281738084 Parse middle delimiters as control sequences 2026-10-20 19:27:14 +08:00
gloamxun 51d82d7e43 Parse control-sequence delimiters after left and right 2026-10-20 19:26:13 +08:00
gloamxun 9c486ee7f2 Cover route-D PDF export and page-level edit replay 2026-10-20 19:24:50 +08:00
gloamxun 1236989edf Refresh the route-D core status document 2026-10-20 19:22:59 +08:00
gloamxun c7b0124369 Let mathop take limits below its body 2026-10-20 19:21:15 +08:00
gloamxun ae8f81b1a2 Place starred operatorname limits below the operator 2026-10-20 19:20:18 +08:00
gloamxun b8a135d2b6 Draw cancel and bcancel math marks 2026-10-20 19:19:13 +08:00
gloamxun 9690dbdbed Add dot and check accent commands 2026-10-20 19:17:14 +08:00
gloamxun dc8282f707 Add common fence delimiter symbols 2026-10-20 19:15:16 +08:00
gloamxun df511602cf Support bmod and pmod 2026-10-20 19:13:53 +08:00
gloamxun 7376acffb2 Draw negated math with a diagonal rule 2026-10-20 19:13:09 +08:00
gloamxun f88fa7fd9d Ignore numbering and limits control words in math 2026-10-20 19:09:44 +08:00
gloamxun c72f612431 Accept the starred operatorname form 2026-10-20 19:09:03 +08:00
gloamxun f3bbe4098b Parse operatorname as upright math text 2026-10-20 19:08:16 +08:00
gloamxun ab35e280f1 Accept tfrac, dfrac and cfrac as fraction aliases 2026-10-20 19:07:28 +08:00
gloamxun 4de329c327 Add a three-paragraph incremental article demo 2026-10-20 19:04:48 +08:00
gloamxun e05caa351b Add explicit math spacing commands 2026-10-20 19:03:07 +08:00
gloamxun 5a9571f792 Preserve math spaces as control-word terminators and text spaces 2026-10-20 19:01:33 +08:00
gloamxun 6876935e60 Treat math style declarations as transparent 2026-10-20 19:00:01 +08:00
gloamxun 495b615220 Encode Latin-1 text bytes in the PDF writer 2026-10-20 18:56:04 +08:00
gloamxun c00edaf357 Paint binomial parentheses around stacked arguments 2026-10-20 18:55:16 +08:00
gloamxun 0446a35b8c Paint sqrt degrees before the radical 2026-10-20 18:53:28 +08:00
gloamxun 17d41cbffd Paint overbrace and underbrace bars 2026-10-20 18:52:34 +08:00
gloamxun 3f1dd0c077 Paint math limits above and below their base 2026-10-20 18:51:49 +08:00
gloamxun b004cd2efb Cover bottom float content painting 2026-10-20 18:50:22 +08:00
gloamxun 34c4f0d84b Offset route-D paragraphs by their left skip 2026-10-20 18:49:27 +08:00
gloamxun 7e45732602 Reserve right skip in route-D paragraph lines 2026-10-20 18:47:52 +08:00
gloamxun 5c0946f990 Seal dedicated float pages in the route-D builder 2026-10-20 18:46:20 +08:00
gloamxun dc14761af7 Document the textfraction float policy 2026-10-20 18:45:12 +08:00
gloamxun e3d5ff3abf Gate bottom floats on the text fraction 2026-10-20 18:44:31 +08:00
gloamxun ea037d66bb Size floats from their vertical content 2026-10-20 18:42:25 +08:00
gloamxun e791c94cfe Paint float content in the route-D display list 2026-10-20 18:40:37 +08:00
gloamxun fb22be1a49 Carry vertical content on route-D floats 2026-10-20 18:37:25 +08:00
gloamxun 25adbc7bf0 Cover italic paragraph PDF resources 2026-10-20 18:36:14 +08:00
gloamxun 0f7ffde050 Cover italic paragraph faces 2026-10-20 18:34:46 +08:00
gloamxun 6b74a17312 Carry paragraph font faces through the display list 2026-10-20 18:32:33 +08:00
gloamxun 96c88d2787 Reflect display font faces in SVG output 2026-10-20 18:30:12 +08:00
gloamxun d40595c7e5 Add per-face PDF font resources 2026-10-20 18:27:14 +08:00
gloamxun 03025de783 Split tall halign tables across pages 2026-10-20 18:25:07 +08:00
gloamxun 1d9b152beb Normalize halign geometry to scaled points 2026-10-20 18:23:29 +08:00
gloamxun 4c64726e61 Record the route-D halign unit mismatch 2026-10-20 18:21:47 +08:00
gloamxun af50f1afa1 Paint route-D float placeholders at page edges 2026-10-20 18:20:32 +08:00
gloamxun 6e1ee13d68 Paint a footnote separator above insertions 2026-10-20 18:19:42 +08:00
gloamxun 493180125a Place insertion material at the page bottom 2026-10-20 18:18:56 +08:00
gloamxun 159bb6a386 Paint insertion material in route-D display lists 2026-10-20 18:17:47 +08:00
gloamxun 8b33051355 Add a route-D PDF backend smoke example 2026-10-20 18:16:55 +08:00
gloamxun eac5bd649a Inject raw PDF specials from display lists 2026-10-20 18:15:42 +08:00
gloamxun da7f580bf0 Emit PDF link annotations from display lists 2026-10-20 18:14:47 +08:00
gloamxun 431bbd14d4 Embed image XObjects in route-D PDF output 2026-10-20 18:13:33 +08:00
gloamxun 7dd3961e21 Emit multi-page route-D PDFs 2026-10-20 18:11:06 +08:00
gloamxun b6fab85f61 Add a minimal PDF writer for route-D display lists 2026-10-20 18:09:55 +08:00
gloamxun 946f8b1b76 Paint math atoms in the route-D display list 2026-10-20 13:46:54 +08:00
gloamxun 38bacdfbd5 Paint paragraph glyphs in the route-D display list 2026-10-20 13:42:58 +08:00
gloamxun d07ff59d31 Add a display-list painter for halign pages 2026-10-20 13:40:01 +08:00
gloamxun bdf3279aed Add the mathstrut item 2026-10-20 13:36:37 +08:00
gloamxun 69e80f6060 Restore the mathop docs line 2026-10-20 13:35:14 +08:00
gloamxun 10ba5c7243 Give mathop its own spacing class 2026-10-20 13:35:00 +08:00
gloamxun 6116bf3553 Add mark and float constructors 2026-10-20 13:34:09 +08:00
gloamxun 30464dd214 Add the double-arrow math accent 2026-10-20 13:32:48 +08:00
gloamxun 0d3067a86d Add the mathring accent 2026-10-20 13:32:05 +08:00
gloamxun f18fc5187f Parse substack into stacked math rows 2026-10-20 13:30:56 +08:00
gloamxun 60949cf91c Record route-D milestone status 2026-10-20 13:29:56 +08:00
gloamxun cd3434ff8e Attach limits labels to overbrace and underbrace 2026-10-20 13:29:02 +08:00
gloamxun 76cc4035ea Add widecheck and dddot math accents 2026-10-20 13:28:10 +08:00
gloamxun cefc3e5289 Parse over-arrow math accents 2026-10-20 13:27:30 +08:00
gloamxun 7802df54a3 Support stakrel as an overset stack 2026-10-20 13:26:49 +08:00
gloamxun 51d65e6fad Add a penalty constructor for vertical breaks 2026-10-20 13:25:37 +08:00
gloamxun b17e16df08 Add a vskip constructor for vertical glue 2026-10-20 13:25:06 +08:00
gloamxun af8a34c2e2 Model boxed math atoms 2026-10-20 13:24:02 +08:00
gloamxun a0bb8be2ac Add the mathinner spacing class 2026-10-20 13:23:28 +08:00
gloamxun 33125d1f16 Keep relation spacing for pmod and negated atoms 2026-10-20 13:20:42 +08:00
gloamxun fd3f0ffae5 Model bmod and pmod math spacing 2026-10-20 13:19:28 +08:00
gloamxun cd0ec782d5 Skip noalign material in halign sources 2026-10-20 13:18:42 +08:00
gloamxun 3639dc0f20 Model negated math atoms 2026-10-20 13:16:54 +08:00
gloamxun 792621d39b Add vertical rules to the page builder 2026-10-20 13:14:34 +08:00
gloamxun a00a2d5148 Apply halign column templates 2026-10-20 13:13:07 +08:00
gloamxun 7250f7f5ca Parse hline rows in halign sources 2026-10-20 13:12:02 +08:00
gloamxun abffe4e7bc Parse halign source spans and omit markers 2026-10-20 13:11:29 +08:00
gloamxun e650177585 Support directional smash options 2026-10-20 13:10:40 +08:00
gloamxun c311938129 Add smash math boxes 2026-10-20 13:10:02 +08:00
gloamxun 4e45a354fe Add phantom math boxes 2026-10-20 13:09:18 +08:00
gloamxun 247cc8bd37 Expose page indices changed by an edit 2026-10-20 13:08:35 +08:00
gloamxun e55b44beac Give big operators display-sized metrics 2026-10-20 13:07:15 +08:00
gloamxun 40af634efd Parse math alphabet wrappers as text metrics 2026-10-20 13:06:14 +08:00
gloamxun 6465915dc1 Place big operator limits above and below 2026-10-20 13:05:36 +08:00
gloamxun 4702bf6ceb Support explicit math atom classes 2026-10-20 13:05:00 +08:00
gloamxun 3fb2b57f21 Add explicit big delimiter sizes 2026-10-20 13:04:06 +08:00
gloamxun a6cf56da6c Grow math delimiters with their body extent 2026-10-20 13:03:14 +08:00
gloamxun 15741c0b9c Add overset and underset math atoms 2026-10-20 13:02:42 +08:00
gloamxun 4e892005cd Add overbrace and underbrace math atoms 2026-10-20 13:02:09 +08:00
gloamxun 833253a936 Add binomial math atoms 2026-10-20 13:01:38 +08:00
gloamxun 639f5e8f8b Parse named math operators as upright text 2026-10-20 13:01:07 +08:00
gloamxun b11fc864f2 Add underline math atoms 2026-10-20 13:00:20 +08:00
gloamxun 053468875e Add upright text atoms inside math 2026-10-20 12:59:45 +08:00
gloamxun ebab0eca05 Accept middle math delimiters 2026-10-20 12:58:30 +08:00
gloamxun 6769a6e80b Parse sqrt degrees and empty delimiters 2026-10-20 12:55:56 +08:00
gloamxun 63927110d9 Add math accent atoms 2026-10-20 12:55:13 +08:00
gloamxun 41456b9d31 Parse left and right math delimiters 2026-10-20 12:54:39 +08:00
gloamxun c545c7ff9a Space math atoms by TeX class 2026-10-20 12:54:03 +08:00
gloamxun b6d55e63dc Parse scripts, fractions and roots into math atoms 2026-10-20 12:53:14 +08:00
gloamxun cd6baba53f Add a math atom box model 2026-10-20 12:52:33 +08:00
gloamxun 9a7404c717 Hyphenate CMR10 paragraphs with TeX patterns 2026-10-20 12:51:30 +08:00
gloamxun c98ec0056f Keep structural units out of text edit reflow 2026-10-20 12:49:15 +08:00
gloamxun 753aac632d Align halign cells and respect topskip on float pages 2026-10-20 12:47:29 +08:00
gloamxun bf24a7c1da Document insertion units 2026-10-20 12:46:03 +08:00
gloamxun fe0defd671 Account for insertions when building pages 2026-10-20 12:45:39 +08:00
gloamxun 9744e14809 Lay out natural-width halign tables 2026-10-20 12:44:24 +08:00
gloamxun 336ca510c8 Reserve space for bottom floats 2026-10-20 12:42:49 +08:00
gloamxun d973b2d1a0 Defer top floats to the next page 2026-10-20 12:41:39 +08:00
gloamxun 17bd2d6237 Add a shipout hook for the output stage 2026-10-20 12:40:14 +08:00
gloamxun bef442684e Collect running marks per page 2026-10-20 12:39:28 +08:00
gloamxun 112a700c9b Place the first box baseline at topskip 2026-10-20 12:38:10 +08:00
gloamxun 3724ab1a00 Reserve insertion material at the page bottom 2026-10-20 12:37:00 +08:00
gloamxun 6af137b17e Reserve top_skip at the start of each page 2026-10-20 12:35:11 +08:00
gloamxun 252963f0fa Honour forced vertical penalties in the M0 page builder 2026-10-20 12:34:07 +08:00
gloamxun 19ecb7fdc6 Record 120pt tolerance candidate measurements 2026-10-20 12:31:39 +08:00
gloamxun 57c3282ff9 Record multi-width pdfTeX line-break differences 2026-10-20 12:30:22 +08:00
gloamxun db72c7775d Set zero parindent in pdfTeX line-break fixtures 2026-10-20 12:29:12 +08:00
gloamxun 812c9d89dc Cover a second pdfTeX line-break fixture 2026-10-20 12:26:53 +08:00
gloamxun cc9cdf1689 Match a pdfTeX paragraph fixture with CMR10 metrics 2026-10-20 12:24:13 +08:00
gloamxun bf5dae3797 Use CMR10 metrics in the M1 paragraph builder 2026-10-20 12:20:49 +08:00
gloamxun e6da4d2fa7 Break paragraphs from character boxes, glue, and penalties 2026-10-20 12:12:41 +08:00
gloamxun 51beb682f0 Add the M1 box/glue/penalty paragraph builder 2026-10-20 12:11:09 +08:00
gloamxun 99dbb5ebb0 Start route D incremental TeX core with M0 checkpoint spike 2026-10-20 12:06:39 +08:00
gloamxun b41a2a9a97 Fit table-cell images to their source aspect ratio 2026-10-20 02:32:42 +08:00
gloamxun 87a81f16cd Embed table-cell images at their grid rectangles 2026-10-20 02:28:45 +08:00
gloamxun d50b4bf560 Set journal abstracts one point below body text 2026-10-20 02:23:57 +08:00
gloamxun 54f610445b Lay out table-cell images as grid placeholders 2026-10-20 02:20:59 +08:00
gloamxun b1b633636a Apply the journal abstract inset to the body block 2026-10-20 02:15:54 +08:00
gloamxun 02218dbf42 Inset journal abstracts like the reference class 2026-10-20 02:11:24 +08:00
gloamxun b8c2be8837 Format numeric bibliography authors with initials 2026-10-20 02:05:40 +08:00
gloamxun 261f0ea278 Fall back to ragged spacing at extreme justification ratios 2026-10-20 02:02:50 +08:00
gloamxun 93bc5ac945 Size PDF figure placeholders from their page aspect 2026-10-20 02:00:40 +08:00
gloamxun 77f672f156 Cover structured SIVP front matter and body layout 2026-10-20 01:53:47 +08:00
gloamxun fcbbbb0ab4 Record the operatorname test count 2026-10-20 01:51:07 +08:00
gloamxun 65b50072af Render operatorname as upright math text 2026-10-20 01:50:49 +08:00
gloamxun 1e7cfd2c85 Record the accent ordering and current test baseline 2026-10-20 01:47:18 +08:00
gloamxun d55f4e4059 Paint bitmap math accents before their base glyph 2026-10-20 01:44:18 +08:00
gloamxun e1060924bf Prevent overfull inline math from overlapping words 2026-10-20 01:37:54 +08:00
gloamxun 5d4920eb29 Prevent overfull inline math from overlapping words 2026-10-20 01:36:52 +08:00
gloamxun d248a84764 Keep tables that fit on a single page intact 2026-10-20 01:30:22 +08:00
gloamxun 9ae7353376 Add a column cursor for the two-column page builder 2026-10-20 01:28:06 +08:00
gloamxun f8dc31cae6 Document the two-column builder requirements 2026-10-20 01:26:11 +08:00
gloamxun 3afa8dc6c1 Track two-column class options in the document model 2026-10-20 01:23:55 +08:00
gloamxun fb361b7df9 Polish journal author and abstract typography 2026-10-20 01:19:40 +08:00
gloamxun 7fa81aa01d Record the journal front matter verification 2026-10-20 01:16:26 +08:00
gloamxun 06cc88809e Capture corresponding authors and class metadata cleanly 2026-10-20 01:15:02 +08:00
gloamxun 5fd5f92bb4 Consume class and theorem declaration options 2026-10-20 01:11:38 +08:00
gloamxun 466abd4ce6 Build structured journal front matter for sn-jnl 2026-10-20 01:08:37 +08:00
gloamxun 82542740e7 Preview SIVP with placeholders for PDF figures 2026-10-20 00:37:56 +08:00
gloamxun ac3e42a201 Record geometry text support and the latest test count 2026-10-20 00:35:12 +08:00
gloamxun 5862664c76 Support geometry text block dimensions 2026-10-20 00:34:58 +08:00
gloamxun 0864536d6d Compile the Huawei E template with tabularx and math vocabulary 2026-10-20 00:30:03 +08:00
gloamxun 07a4dcdda1 Cover eqref and math accent rendering 2026-10-20 00:20:14 +08:00
gloamxun e77181e997 Add eqref, math accents, and named undefined-command errors 2026-10-20 00:18:24 +08:00
gloamxun f4d477695f Add long arrow math symbols and aligned regression tests 2026-10-20 00:09:08 +08:00
gloamxun 3622d40043 Cover longtable headers with math body rows 2026-10-20 00:06:27 +08:00
gloamxun 972b7635d2 Cover math scripts in longtable cells 2026-10-20 00:04:11 +08:00
gloamxun 9e3164adf6 Support resizebox content and PDF image placeholders 2026-10-20 00:03:10 +08:00
gloamxun 3be8cefe46 Support tabular-star specs, escapes, and SIVP math commands 2026-10-19 23:59:24 +08:00
gloamxun c1a7dedd6a Support nested if-prefixed conditionals, char, and SIVP math/preamble commands 2026-10-19 23:55:03 +08:00
gloamxun 64f4446113 Cover TeX if branches and count registers 2026-10-19 23:42:29 +08:00
gloamxun 7f25075742 Add if/ifx conditionals, count registers, and SIVP class compatibility 2026-10-19 23:42:05 +08:00
gloamxun c3ae426a10 Cover longtable row and rule rendering 2026-10-19 23:29:47 +08:00
gloamxun b599f92516 Define table and figure counters for longtable headers 2026-10-19 23:24:23 +08:00
gloamxun 682604ae44 Support longtable environments and common class declarations 2026-10-19 23:23:02 +08:00
gloamxun 3eb4e81956 Support common class declarations and page length registers 2026-10-19 23:15:22 +08:00
gloamxun 34c8b7d6ec Avoid byte slicing panics in CJK error messages 2026-10-19 23:03:24 +08:00
gloamxun 6e046575ac Cover horizontal centering of the natural-width table 2026-10-19 22:54:25 +08:00
gloamxun 9b367e87ee Use a 110-glyph minimal font tier for ASCII documents 2026-10-19 22:49:30 +08:00
gloamxun 769e3cdf17 Embed the official ORCID logo as a PDF image 2026-10-19 22:43:24 +08:00
gloamxun 69edbf56b6 Skip the unused print output intent to shrink PDFs 2026-10-19 22:18:58 +08:00
gloamxun 8fea8880b5 Raise the ORCID badge label toward the center 2026-10-19 22:17:13 +08:00
gloamxun 4735d75c1f Compress embedded font streams in the PDF writer 2026-10-19 22:15:27 +08:00
gloamxun 369472e7f7 Compact minimal-tier serif glyph ids 2026-10-19 22:13:03 +08:00
gloamxun 79305d7c79 Use a minimal font tier for Latin-1 documents 2026-10-19 22:11:54 +08:00
gloamxun aaa9dee477 Shrink bundled font subsets with retained ids and kern 2026-10-19 22:06:23 +08:00
gloamxun ec45ce0694 Bundle reserved-glyph font subsets for covered documents 2026-10-19 22:02:30 +08:00
gloamxun ea14b3edbf Embed a single monospace face to shrink PDFs 2026-10-19 21:42:17 +08:00
gloamxun 2076da8f21 Annotate ORCID author badges with their profile links 2026-10-19 21:37:17 +08:00
gloamxun 05d7980561 Annotate href labels with PDF link targets 2026-10-19 21:33:26 +08:00
gloamxun 88646c9453 Center the white iD label in the ORCID badge 2026-10-19 21:29:36 +08:00
gloamxun 4c2ec0a402 Match the reference table width to 0.1 mm 2026-10-19 21:27:14 +08:00
gloamxun e4c5b0cb32 Draw rounded ORCID badges in PDFs 2026-10-19 21:25:31 +08:00
gloamxun 5d6d51536f Round preview ORCID badges 2026-10-19 21:22:56 +08:00
gloamxun 3b270d749d Embed fonts and add PDF link annotations 2026-10-19 21:18:58 +08:00
gloamxun 2856506d65 Embed text fonts and fix preview table rule coordinates 2026-10-19 21:07:25 +08:00
gloamxun b119c57e8e Record the final arXiv alignment snapshot 2026-10-19 19:26:44 +08:00
gloamxun 0d70318a12 Scale the ORCID badge label for legibility 2026-10-19 19:25:33 +08:00
gloamxun d73d6334fc Center the vector ORCID badge label 2026-10-19 19:23:53 +08:00
gloamxun ec6826619b Draw ORCID author badges as native vector marks 2026-10-19 19:22:16 +08:00
gloamxun ae7e27116f Record the failed inline ORCID bitmap experiment 2026-10-19 19:17:30 +08:00
gloamxun 4edd345a01 Document the aligned title-page line and remaining annotation gaps 2026-10-19 19:13:30 +08:00
gloamxun 6c55686849 Keep the closing title-page line above the footnote 2026-10-19 19:12:39 +08:00
gloamxun aed9b5bb5f Plan the remaining arXiv alignment work 2026-10-19 19:10:42 +08:00
gloamxun f167b4f4d1 List link support in the capability matrix 2026-10-19 19:10:06 +08:00
gloamxun 41c928788e Document the PDF annotation blocker 2026-10-19 19:07:12 +08:00
gloamxun 6216201d7d Assert links in the compatibility example 2026-10-19 19:06:27 +08:00
gloamxun 08d31bb4d9 Cover links in the compatibility example 2026-10-19 19:05:29 +08:00
gloamxun 26f66d871a Document orcidlink 2026-10-19 19:03:32 +08:00
gloamxun da77f19d0f Support orcidlink badges 2026-10-19 19:02:56 +08:00
gloamxun d9befd4d87 Render ORCID author links as green badges 2026-10-19 19:01:12 +08:00
gloamxun 7c4edbb1f1 Cover preprint metadata spacing 2026-10-19 18:57:57 +08:00
gloamxun 6f71414d69 Tighten the title footnote reserve 2026-10-19 18:55:37 +08:00
gloamxun 09414e1fe1 Align preprint metadata spacing with the reference 2026-10-19 18:54:22 +08:00
gloamxun 8c07d3442e Keep body text clear of the title footnote area 2026-10-19 18:51:25 +08:00
gloamxun 247893282b Match the reference table width for math cells 2026-10-19 18:41:47 +08:00
gloamxun 0c615c8e82 Collect footnotes inside figure and table captions 2026-10-19 18:39:16 +08:00
gloamxun 6414770de7 Cover hyperlink colour across line breaks 2026-10-19 18:34:54 +08:00
gloamxun 9dc1f59f8e Reserve title footnote space on the first page 2026-10-19 18:32:10 +08:00
gloamxun 09781d40e9 Render hyperlinks with hyperref green colour 2026-10-19 18:29:24 +08:00
gloamxun a8b20563fb Match arxiv leading and title spacing 2026-10-19 18:19:45 +08:00
gloamxun ff509c2d59 Reserve depth at the bottom of the page frame 2026-10-19 18:15:00 +08:00
gloamxun 71bd01c82c Hang plainnat bibliography continuation lines 2026-10-19 18:09:11 +08:00
gloamxun 2fca019237 Add natbib a/b year suffixes for duplicate author-year entries 2026-10-19 18:04:19 +08:00
gloamxun 87b6b6e44e Align preprint title top margin with TeX 2026-10-19 18:00:24 +08:00
gloamxun d4e52dc225 Support multicolumn spans and partial table rules 2026-10-19 17:53:26 +08:00
gloamxun ca5cb0b8af Use Base-14 fonts when possible and center natural-width tables 2026-10-19 17:40:04 +08:00
gloamxun 1da9e0dde9 Preserve inline emphasis in preprint title runs 2026-10-19 17:12:23 +08:00
gloamxun d211889e93 Polish preprint title details and plainnat bibliography formatting 2026-10-19 15:53:47 +08:00
gloamxun 7f1f202de1 Add abstract quotations, unnumbered paragraphs, and author-year citations 2026-10-19 15:39:02 +08:00
gloamxun 3406f84e86 Expand fancy headers at document start and add header rules 2026-10-19 15:28:54 +08:00
gloamxun 4991bdfcfc Render arxiv-style preprint title blocks 2026-10-19 15:23:13 +08:00
gloamxun 8d5cbc69ba Fix PDF rule placement, lipsum text, 10pt default, and page decorations 2026-10-19 15:02:16 +08:00
gloamxun e7bcdf6c53 Place bottom tables at the page bottom 2026-10-19 14:43:33 +08:00
gloamxun 6658a155fc Queue top table floats and let text flow around them 2026-10-19 14:42:06 +08:00
gloamxun 7ad3c327ec Capture vertical material in vbox and vtop 2026-10-19 14:34:22 +08:00
gloamxun 5e9552d785 Allow documents to replace the title block 2026-10-19 14:32:35 +08:00
gloamxun 23cf1f13de Queue top figures and flow following text around them 2026-10-19 14:28:49 +08:00
gloamxun 5a54386dee Start chapters on a new page 2026-10-19 14:24:50 +08:00
gloamxun a798221817 Add chapter headings and chapter-prefixed numbering 2026-10-19 14:23:53 +08:00
gloamxun 6d4aa37189 Add dotted leaders to generated contents entries 2026-10-19 14:20:30 +08:00
gloamxun 1b0ce27ed3 Honour the centering paragraph declaration 2026-10-19 14:18:42 +08:00
gloamxun 2c8d5e12d8 Honour raggedright and raggedleft paragraph alignment 2026-10-19 14:16:50 +08:00
gloamxun c7b7660049 Add an unnumbered heading for the abstract environment 2026-10-19 14:10:59 +08:00
731 changed files with 263815 additions and 615 deletions

No files matched your search

Generated
+970 -8
View File
File diff suppressed because it is too large. Load diff
+12 -1
View File
@@ -11,14 +11,17 @@ name = "texrra"
path = "src/main.rs"
[workspace]
members = ["crates/texrra-core"]
members = ["crates/texrra-core", "crates/texrra-tex-core"]
[dependencies]
texrra-core = { path = "crates/texrra-core", features = ["serde"] }
texrra-tex-core = { path = "crates/texrra-tex-core" }
flate2 = "1.1"
hayro-svg = { version = "=0.9.0", default-features = false, features = ["embed-cmaps"] }
hyphenate = { path = "vendor/hyphenate" }
genpdf = { version = "0.2.0", features = ["images"] }
printpdf = "0.3.4"
lopdf = "0.26"
image = { version = "0.23.12", default-features = false, features = ["png", "jpeg", "bmp"] }
common = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0", features = ["serde"] }
boxworks = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" }
@@ -29,11 +32,15 @@ texlang-stdlib = { git = "https://github.com/jamespfennell/texcraft", rev = "c1d
texlang-common = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" }
texcraft-stdext = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
rmp-serde = "1.3"
tiny_http = "0.12"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
ttf-parser = "0.25.1"
[patch.crates-io]
printpdf = { path = "vendor/printpdf" }
genpdf = { path = "vendor/genpdf" }
[patch."https://github.com/jamespfennell/texcraft"]
@@ -41,4 +48,8 @@ texlang = { path = "vendor/texlang" }
texlang-stdlib = { path = "vendor/texlang-stdlib" }
[dev-dependencies]
tungstenite = "0.30"
serde_json = "1"
[target.'cfg(target_os = "linux")'.dev-dependencies]
libc = "0.2"
+275 -43
View File
@@ -1,10 +1,122 @@
# texrra engine
Rust-native, Typst-inspired incremental LaTeX engine with a live preview
server. Typesetting is implemented in Rust; the engine does not invoke XeLaTeX,
LuaLaTeX, or pdfLaTeX. The web frontend is a separate repository,
[`texrra-web`](https://git.iloveuulove.me/gloamxun/texrra-web), served by this
engine as static files.
Texrra is building a TeX engine for live editing of existing LaTeX projects.
It tracks inputs and compilation state, reuses eligible work after edits,
and publishes updated pages with source locations. The delivery targets are
a library, a CLI, and editor integration. The current Route-D implementation
is the development baseline. Upstream TeX components are candidates for reuse
where their state, file effects, and cancellation can be verified.
The [product goal](docs/NATIVE_PRODUCT_GOAL.md) defines compatibility and live
preview acceptance. The [publisher matrix](docs/PUBLISHER_TEMPLATE_MATRIX.md)
covers original journals, two-column journals, conferences, and arXiv.
The [local beta guide](docs/NATIVE_BETA.md) explains how to prepare a bundle,
open a project in the native editor, and export a PDF.
## Native execution bootstrap
The current Route-D entry is available through the developer CLI and the native
editor example. Its implementation and remaining work are tracked in the
[stage progress](docs/P2_M1_PROGRESS.md). The separate frontend repository
is [texrra-web](https://git.iloveuulove.me/gloamxun/texrra-web).
Native fonts come from an explicit resource World. For the checked-in examples,
configure the actual TFM/PFB directories and an installed font-map directory:
```sh
export TFMFONTS="$PWD/crates/texrra-tex-core/assets"
export T1FONTS="$PWD/assets/fonts"
# Example TeX Live map directory on this development system; configure yours.
export TEXFONTMAPS=/var/lib/texmf/fonts/map/pdftex/updmap
cargo run --release -- native examples/native-bootstrap/main.tex /tmp/bootstrap.pdf
cargo run --release -- native --initex --etex examples/native-bootstrap/dynamic-fonts.tex /tmp/fonts.pdf
cargo run --release -- native --job --initex --etex examples/native-bootstrap/native-job.tex /tmp/native-job.pdf
cargo run --release -- native --job --initex --etex examples/native-bootstrap/device.tex /tmp/device.pdf
```
`--job` selects actual online native page/output/shipout execution. It exports
only boxes really shipped by the token executor; deferred I/O runs when its
original material is shipped. Each shipout captures its actual paper,
origin/offsets and mag; zero paper dimensions use the real box's dimensions.
The logical box and actual font resources are retained, with a common physical
transform for PDF/SVG. [Native mag/true and device state](docs/NATIVE_DEVICE.md)
records the supported semantics and remaining PDF configuration/precision work. The entry without
`--job` remains a list-measurement tool for existing algorithm gates; its host
canvas does not certify native pagination. There is no automatic fallback
between these targets. See [native pages and remaining device work](docs/NATIVE_PAGES.md).
INITEX starts with actual nullfont and zero layout dimensions. Non-INITEX
bootstrap loads its initial cmr10 through World. The current native job reports
missing resources directly.
Use `--texmf-root`, resource search environment variables and `--input-policy`
for distribution/project resources; `--resource-manifest` records actual reads,
versions and negative lookups, including failed jobs. The CLI defaults to TeX
8-bit input. Use `--input-profile xetex --etex` for the native XeTeX language
and output profile, or `--input-profile unicode` for the existing scalar-input
mode. Build and load format images with the same profile.
This entry executes native tokens, expansion, scoped state, real streams,
measured h/v/math lists, paragraph breaking and display transitions without v1
or source preprocessing. It now carries actual sized FontId resources through
text, math, geometry, SVG and PDF. Live fontdimen and em/ex affect their real
consumers; output uses actual map/encoding/PFB resources. See
[native font execution and boundaries](docs/NATIVE_FONT_EXECUTION.md).
The native editor example exercises the shared compile session and page
updates. The production HTTP routes still use the older implementation.
Format boot, active compatibility gaps, and whole-project results are tracked
in the [stage progress](docs/P2_M1_PROGRESS.md).
[Streaming TFM keep/pass/boundary execution](docs/NATIVE_FONT_PROGRAMS.md) is
connected to actual lists. [Owned discretionary branches and actual ligature
hyphenation/reconstitution](docs/NATIVE_DISCRETIONARIES.md) now feed line breaking,
packing, diagnostics and output. [Two-pass mathematical noad ligature/kern and
operator limits/display/rebox execution](docs/NATIVE_MATH_PROGRAMS.md) also use
actual font instances and list consumers. [Canonical raw paragraph line boxes,
running rules/overfull markers, actual shifts/unboxing/lastbox and native math
subboxes](docs/NATIVE_LISTS.md) are connected. Nested boxes suspend and restore
actual math/display frames; output and math reuse the same raw-list traversal.
[Original-list vert_break/vsplit, live split parameters and per-class split marks](docs/NATIVE_SPLITTING.md)
now execute. Paragraph/adjusted-hbox/display marks migrate at actual pack time;
mark expansion retains real input contexts and byte diagnostics.
[Online page contributions, real output groups/shipout, page marks and deferred
file I/O](docs/NATIVE_PAGES.md) now execute natively. The four-page reference
job matches all 174 words, actual auxiliary bytes and all four raster pages.
Real mag/true, actual true font sizes and per-shipout paper/origin/offsets now
execute; the 15-job/29-page device oracle passes. [Real PDF file state, versions,
compression, object streams/xref and original-sp precision](docs/NATIVE_PDF_CONFIG.md)
now execute. The new 28-configuration/56-page and retained device matrices have
zero word-box, paper and raster XOR differences. Independent 105-page object
stream rollover also passes. Native jobs with `\pdfoutput=0` can write binary DVI.
Specify the DVI destination explicitly with `texrra native --load-format latex.tfx
--input-profile tex8bit input.tex output.dvi`. The writer serializes the actual
shipouts. DVI drivers receive special payloads in their original page order.
[DVI evidence](docs/P2_M1_PROGRESS.md#原生-dvi-出页设备)
[Actual PK resolution, bitmap decoding, Type3 output and shared text cursor](docs/NATIVE_PK_FONTS.md)
now execute; 384 independent glyphs and a 43-job/86-page oracle pass with zero
bitmap/word-box/paper/raster differences. Missing devices/resources fail.
[Actual native ownership/resource statistics and page-break diagnostics](docs/NATIVE_STATISTICS_PAGE_TRACE.md)
now execute; 16 jobs/48 pages match reference ink and 216 exact page diagnostics.
Trace controls preserve native PDF bytes. [Actual paragraph traces, canonical-zero glue
and owned ordinary side-script lists](docs/NATIVE_PARAGRAPH_TRACE.md) also execute;
8 jobs/32 pages have 24 exact reports and 5436 pass/decision lines with zero word/raster
differences. Other tracing consumers, compound math fields, insertions, format images, real
NFSS/article and compile sessions remain required by P2-M1. Unsupported commands and resources are explicit errors.
Component contracts and independent reference checks:
- [Input contexts/show](docs/NATIVE_INPUT_CONTEXT.md), [input profiles](docs/NATIVE_INPUT_PROFILE.md),
[job time/file streams](docs/NATIVE_JOB_IO.md), [quantities](docs/NATIVE_QUANTITIES.md).
- [Paragraphs](docs/NATIVE_PARAGRAPHS.md), [boxes/vpack](docs/NATIVE_BOXES.md),
[interline penalties](docs/NATIVE_INTERLINE_PENALTIES.md), [sfcode](docs/NATIVE_SFCODE.md),
[case/language data](docs/NATIVE_LANGUAGE_DATA.md).
- [Inline math](docs/NATIVE_MATH_EXECUTION.md), [display transitions](docs/NATIVE_DISPLAY_MATH.md),
[accents](docs/NATIVE_FONT_STATE_ACCENTS.md), [delimiters](docs/NATIVE_DELIMITERS.md),
[box/list diagnostics](docs/NATIVE_BOX_DIAGNOSTICS.md).
- [Integer TFM](docs/NATIVE_TFM_LOADING.md), [font catalog](docs/NATIVE_FONT_CATALOG.md),
[font program work remaining](docs/NATIVE_DYNAMIC_FONTS.md).
The UI and compatibility features described below belong to the existing
application; they do not certify native token-kernel LaTeX portability.
## Repository layout
@@ -12,12 +124,13 @@ Clone both repositories as siblings so the engine can discover the frontend:
```
texrra/
engine/ # this repository: Rust engine and HTTP server
web/ # texrra-web: static editor frontend
texrra-engine/ # this repository: Rust engine and HTTP server
texrra-web/ # texrra-web: static editor frontend
```
The server resolves the frontend from `TEXRRA_WEB_DIR` when set, otherwise from
`../web` and then `./web`. It serves `index.html`, `styles.css`, `app.js`, and
a sibling `web` or `texrra-web` directory (`./web`, `./texrra-web` and their
`../` forms). It serves `index.html`, `styles.css`, `app.js`, and
`favicon.svg`; preview font faces are generated by the engine at `/fonts.css`
and `/fonts/*.ttf`.
@@ -121,14 +234,15 @@ the `.tex` file passed to `serve`.
It handles document metadata, `\maketitle`, and `\today` (UTC),
A4 pages, `geometry` margins (`margin`, `top`, `right`, `bottom`, `left`,
`hmargin`, and `vmargin` with `mm`, `cm`, `in`, `pt`, or `bp` units), paragraphs,
numbered and starred heading levels, paragraph indentation (`\parindent`),
numbered and starred heading levels (article sections; `report`/`book` chapters with sections numbered `1.1`), paragraph indentation (`\parindent`),
`\hfill`, serif/sans/monospaced text, true small caps, itemize/enumerate lists,
page
breaks, basic display and inline math, figures, simple tables,
section/figure/table references, and numeric citations from a manual bibliography
or a local `.bib` file. A4 pages use 25 mm margins unless
`geometry` sets them. Liberation Serif is embedded in the PDF for Latin and math
glyphs; CJK text uses an installed fallback font.
breaks, basic display and inline math, figures, tables whose cell widths use Computer Modern metricss,
section/figure/table references, numeric citations from a manual bibliography or a
local `.bib` file, and natbib-style author-year citations for the arXiv template. A4 pages use 25 mm margins unless
`geometry` sets them. The PDF always embeds its Liberation Serif/Mono/Sans
faces (and any CJK fallback), so glyphs do not depend on fonts installed in the
reader; font programs and ToUnicode maps are Flate-compressed, so PDFs are larger than Base-14 output but render reliably.
### LaTeX compatibility layer
@@ -140,7 +254,9 @@ parameterization commands:
- `\newlength`, `\setlength`, and `\addtolength` (skip registers), plus
`\newcounter` / `\setcounter` / `\addtocounter`.
- `\newcommand`, `\renewcommand`, `\providecommand`, `\def`, `\let`, and
legacy commands such as `\setlength`-style kernel macros.
legacy commands such as `\setlength`-style kernel macros; `\long`/`\global`/
`\outer`/`\protected` definition prefixes, `\gdef`, and
`\protected@edef`/`\protected@xdef` are accepted.
- `\newenvironment` / `\renewenvironment` are accepted; layout-critical
environments (`abstract`, `figure`, `table`, lists, `tabular`) keep the
engine's native behavior, and redefinitions of the structural commands
@@ -150,6 +266,8 @@ parameterization commands:
`\newgeometry`.
- Package files are read with `@` as a letter, so `\@title`-style internals
tokenize correctly.
- The `abstract` environment indents its body as a quotation, and `\paragraph`
produces an unnumbered bold run-in heading.
`\documentclass[options]{class}` parses class options, accepts the built-in
`article`, `report`, `book`, `letter`, `minimal`, and `standalone` classes, and
@@ -176,20 +294,24 @@ Page styles are painted in both the PDF and the SVG preview:
`\thispagestyle{...}` overrides one page, and fancyhdr's `\fancyhead`/
`\fancyfoot` plus `\lhead`/`\chead`/`\rhead`/`\lfoot`/`\cfoot`/`\rfoot`
place runs in the left, center, or right slot. `\thepage` is resolved when the
page is painted, so the footer shows the real page number. The default style is
page is painted, so the footer shows the real page number. Decoration tokens
are expanded at the start of the document, after packages have renewed macros
such as the short title, and fancy headers get the usual 0.4pt rule below them.
The default style is
`plain` (a centered page number).
The following packages are accepted as built-ins: `geometry`, `graphicx`,
`amsmath`, `amssymb`, `amsfonts`, `booktabs`, `hyperref`, `cite`, `natbib`,
`inputenc`, `fontenc`, `url`, `nicefrac`, `microtype`, `cleveref`, `lipsum`,
`doi`, `authblk`, and `fancyhdr`. Their commands are approximated where they
affect text (`\url` becomes breakable monospace, `\nicefrac`, `\cref`,
affect text (`\url` becomes breakable monospace (a `~` outside URLs becomes a space, while URLs keep their tildes), `\nicefrac`, `\cref`,
`\doi`, `\lipsum`, `\verb`); `\hypersetup` and `\microtypesetup` remain
PDF-backend no-ops, while fancyhdr's page decorations are painted natively.
Figure and table captions are numbered (`Figure 1: ...`, `Table 1: ...`), and
`\ref` to a figure/table label resolves to that number. Display math that is
wider than the text column is scaled to fit the column. Latin text is hyphenated
wider than the text column is scaled to fit the column; route-D instead
splits wide display formulas at top-level operators. Latin text is hyphenated
with plain TeX's English patterns (two letters before and three after the
hyphen) through the Knuth–Plass line breaker; math and CJK text are not
hyphenated.
@@ -298,7 +420,11 @@ block.
The `center` environment is a block: its content wraps at the text width and
every line is centered without justification (natural spaces), so
`\begin{center}\url{...}\end{center}` and centered short text match LaTeX.
`\centering` inside a paragraph is still a no-op.
`\centering`, `\raggedright`, and `\raggedleft` are paragraph-level
declarations: the affected runs use natural space widths, the declaration is
scoped by groups and the matching environments, centered lines are offset by
half the leftover width, and ragged-left/right lines are not stretched to the
margin.
`\rule[raise]{width}{height}` is rendered as a filled rectangle in both the
PDF and the SVG preview, including raised and dropped rules; a zero-thickness
@@ -310,18 +436,39 @@ a 0.4pt frame, and painted in both the PDF and the SVG preview.
Base font-size class options `10pt`, `11pt`, and `12pt` now set the body
size and propagate through headings, title material, lists, tables, block
boxes, footnotes, and the default paragraph indent.
Known gaps for full document classes: custom `\maketitle` implementations
are ignored (the engine title layout is used), `\parbox`/`\minipage` are
block-level rather than inline, `\vbox` and `\vtop` map to a full-width block
box rather than true nested VBox material, and the abstract prints as body text
without an "Abstract" heading.
boxes, footnotes, and the default paragraph indent. The article default is
`10pt`, matching LaTeX.
A document-level `\renewcommand{\maketitle}` replaces the engine title block.
Journal classes that distribute front matter through commands such as
`\author`, `\affil`, `\abstract`, and `\keywords` are captured as structured
metadata. The `sn-jnl` class then renders a journal title block: centered title,
numbered author lines with affiliation marks, affiliation list, e-mail line,
abstract, and keywords. Class-internal `\maketitle` layout is still not
executed; the engine builds the block from the captured metadata.
When a document loads `arxiv.sty`, the engine switches to a native preprint
title style: top/bottom title rules, small-caps title with inline emphasis
preserved (e.g. the italic `arxiv` in the class example), `\undertitle`,
two-column author blocks with affiliations and monospaced e-mail addresses,
a long date, and `\thispagestyle{empty}` on the first page. Class and package
files that replace `\maketitle` itself are still ignored, so box-level
template code cannot break the native layout. Ordinary text is now placed on
a TeX baseline grid (1.2em line height, 0.8em ascent) instead of the fallback
TrueType font's larger ascent/descent, which matches LaTeX line spacing and
page breaks. Known gaps for full document classes: `\parbox`/`\minipage` are
block-level rather than inline, and `\vbox`/`\vtop` capture vertical
material but do not form an independent natural-width box with its own
baseline.
`\footnote{...}` captures its content, emits a superscript marker, reserves
space on the page where the paragraph ends, and paints the notes with a
separator rule at the bottom of the page. `\thanks{...}` is a footnote in the
title or author block and is painted at the bottom of the first page. Footnotes
inside captions, floats, or arbitrary boxes are not collected yet.
separator rule at the bottom of the page. Footnote lines are painted in body
coordinates so they stay below the text block rather than overlapping it.
`\thanks{...}` is a footnote in the title or author block and is painted at
the bottom of the first page. Its measured height is reserved before body
placement, so the last body line stays above the footnote area. Footnotes
inside figure and table captions are collected and follow the caption's page;
footnotes inside floats or arbitrary boxes are not collected yet.
Basic `\input{file}` imports are read relative to the main `.tex` file. Imported
files participate in source mapping and frontend cache invalidation. Local style
@@ -338,23 +485,42 @@ platform path separator for multiple directories). A local style can use
local package options, arbitrary TeX code, and the full LaTeX package ecosystem
are not implemented. These LaTeX command
definitions support up to nine parameters, including one optional first
parameter with a default value. Unknown packages fail with a clear error.
parameter with a default value. Unknown packages fail with a clear error. Hyperlinks (`\href`, `\url`, and
resolved citations) use hyperref's green link colour; `\orcidlink{id}`
renders the bundled official ORCID logo (2.2 mm) linked to `orcid.org`. Visible `\url` text also
emits a real PDF `/Link` URI annotation; `\href` and ORCID-name links still
need their target URL carried through the document model.
`\includegraphics` embeds PNG, JPEG, or BMP files relative to the `.tex` file.
`\includegraphics` embeds PNG, JPEG, or BMP files relative to the `.tex` file, with `width=`/`height=`/`scale=`/`keepaspectratio` sizing.
It supports `width`, `height`, and `scale`; width and height accept physical
units or fractions of `\linewidth`. Images with transparency are not supported
by the current PDF dependency. Basic `tabular` rows become equal-width PDF
columns; `l`, `c`, `r`, and paragraph (`p{...}`) columns are supported, as are
full-width `\hline` and `booktabs` rules. Spanning cells, partial `\cline` rules,
and multi-page table headers are not implemented. `\label`, `\ref`, and `\cite`
by the current PDF dependency. `tabular` rows use natural column widths
(content width plus 6pt `\tabcolsep`), are centered in the text block, and draw
`\hline`/`\booktabs` rules exactly over the table columns; `l`, `c`, `r`, and
paragraph (`p{...}`) columns are supported. `\multicolumn{n}{align}{...}`
spans columns, `\cmidrule(r){a-b}` and `\cline{a-b}` draw partial rules over
a column range, and spanning cells distribute their width over the covered
natural columns; the resulting width matches the reference XeLaTeX output.
In route-D, `\halign`/`\calign` sources support `l`/`c`/`r`/`p{width}` cells, explicit `\tabskip`, `@{}`/`@{\hspace{...}}` column expressions, `\noalign{\vskip ...}` row glue, booktabs rule weights (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt) with `\cmidrule(lr){a-b}` trims and ranges, row-level page splitting that repeats the column widths, longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) whose continuation chunks repeat the head rows and paint the foot block once, and LaTeX `tabular` and `longtable` sources mapped onto the same alignment path, where `\multicolumn{n}{align}{...}` cells span columns with the requested alignment and `\cline{a-b}` draws partial 0.4pt rules. Figures honor `[htbp]`
placement hints (`[t]` is deferred to the top of the next page, `[b]` to the
page bottom, `[p]` to a float page, `[h]` stays in the flow); a standalone
`\vspace{...}` between paragraphs becomes vertical glue with its `plus`/`minus`
parts; tables honor
`[t]` by deferring the caption and rows to the next page, `[b]` at the page
bottom, and `[p]` with a float page. `\label`, `\ref`, and `\cite`
resolve section, figure, table, and bibliography numbers. `\bibliography{file}`
reads a local `.bib` file (the `.bib` extension is optional) and formats common
author/editor, title, journal, booktitle, volume, number, pages, publisher,
institution, school, organization, edition, address, month, note, and year fields.
BibTeX `@string` macros and single-level `crossref` inheritance are supported.
Manual `thebibliography` entries also work. Custom `.bst` sorting and formatting,
author-year citation styles and page-number references (`\pageref`) are not
implemented.
Manual `thebibliography` entries also work. Documents loading `natbib` or
`arxiv.sty` render `\citet`/`\citep` as author-year citations, format `.bib`
entries in plainnat order (`First Last`, `In ...`, `pages`, publisher/year),
add deterministic year suffixes (`2014a`, `2014b`) when several entries share
an author and year, indent continuation lines in the plainnat hanging style,
and omit numeric bibliography labels; other documents keep
numeric citations. Custom `.bst`
sorting/formatting and page-number references (`\pageref`) are not implemented.
A paragraph starts with the current `\parindent` (17pt by default); the
indent is recorded per paragraph and follows group scoping, `\setlength`,
@@ -417,6 +583,25 @@ variant for delimiters and large display operators, and builds taller glyphs
from the font's MATH assembly parts. `\\left...\\right` target sizing follows
the assignable TeX parameters `\\delimiterfactor` (default 901) and
`\\delimitershortfall` (default 5pt), including local and global assignments.
Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Characters outside a program's encoding fall back per glyph to a Liberation subset, so the ASCII letters of an accented word still use Computer Modern and Greek text keeps its Unicode text under PDF extraction, including capital Omega, because the embedded Type1 faces carry a ToUnicode CMap built from the requested characters rather than relying on glyph names. Accent commands such as `\'`, `` \` ``, `\"`, `\^`, `\~`, `\c`, `\v` and `\=` compose precomposed Unicode letters and fall back to the base letter plus a combining mark. `\textsuperscript` and `\textsubscript` set a 70% run raised or lowered by 0.4em. `\MakeUppercase` and `\MakeLowercase` (also `\uppercase`/`\lowercase`) transform their braced text while keeping the surrounding face. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. A `\textcolor{name}{...}` run paints in one of the standard named colours in both the SVG preview and the PDF, and a leading `\\color{name}` switch colours the rest of its paragraph (`\definecolor` supports rgb, RGB, gray, HTML and cmyk models, `\pagecolor{name}` fills the page background, a `name!percent!other` spec mixes two named colours linearly, the second defaulting to white, and `\hypersetup{urlcolor=...}` colours `\href` labels, and `\colorbox{name}{...}` paints a filled rectangle behind its text, and `\fcolorbox{frame}{background}{...}` draws a 0.4pt frame around that rectangle, while `\fbox{...}` draws the same frame without a background).. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{<size>}{<baselineskip>}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt), and `\linespread{factor}` (or `\renewcommand{\baselinestretch}{factor}`) scales that baseline; a size command inside a paragraph overrides the class default and keeps its own glyph size in that run. Inline math inside a styled run keeps its math face while the surrounding text retains its style. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue; a counter declared with `\newcounter{name}` starts at zero and can be changed by `\setcounter`/`\addtocounter`, and a length declared with `\newlength{\name}` can be set by `\setlength{\name}{...}` and then used as the value of a later `\setlength{\parindent}{\name}`, and `\addtolength{\name}{...}` adds to such a length, so class code that stores its dimensions in named lengths takes effect. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. A leading `\noindent` starts its paragraph flush with the measure. Page numbers print centred below the text block, `\setcounter{page}` offsets the printed number, `\addtocounter{page}` shifts it (`\pagenumbering` resets it to 1), and `\pagenumbering{roman|Roman|alph|Alph|arabic}` changes their format and `\pagestyle{empty}` suppresses them on every page and `\thispagestyle{empty}` on the first page. `\hypersetup{pdftitle=...}` writes the PDF Info dictionary (title, author, subject and keywords, UTF-16BE for non-ASCII text), each numbered heading becomes a PDF bookmark nested by heading level, `\title`, `\author` and `\date` are captured from the preamble, `\today` expands to the current date, and `\maketitle` expands into a centered title block at the article class sizes (using today's date when `\date` is absent and none for `\date{}`). `\section`, `\subsection`, `\subsubsection`, `\paragraph` and `\subparagraph` advance five-level article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/Line truncated
Inline `$...$` and `\(...\)` math is laid out inside 10pt paragraphs (larger sizes keep the delimiters literal). `\newcommand`/`\renewcommand`/`\DeclareRobustCommand` definitions are captured from the preamble (and `\providecommand` only fills a name that is still undefined) and expanded textually, including numbered arguments and one `[default]` optional first argument; TeX's `\def` parameter texts and `\let` aliases are executed the same way, `\edef`/`\xdef` expand their bodies once at definition time and `\csname...\endcsname` builds the named control sequence, `\expandafter` runs the macro after its prefix once (chained zero-argument prefixes expand in order), and `\newenvironment` definitions wrap their bodies with the declared begin/end material. `\newif` flags select between `\if...\else...\fi` branches, with assignments honoured in the preamble or the body, so class conditionals like `\ifdraft` work, and `\ifdefined\name` tests whether a macro is declared. `\ifnum` compares integers from literals, `\newcount` registers or `\value{counter}`, and `\ifx` compares token meanings (two macros are equal when their parameter text and body match) `\ifcase <n>` chooses the n-th `\or` branch and falls back to `\else` when the value is out of range.. the scratch registers `\dimen0`-`\dimen255` and `\skip0`-`\skip9` hold dimensions and glue with the same assignment and `\advance` forms, and `\count0`-`\count9` take assignments, `\advance`, `\multiply` and `\divide` and print through `\the`/`\number`, while `\newcount\name` declares an integer register whose value `\name= `\dimexpr ... \relax` evaluates `+`, `-`, `*` (by an integer) and `/` over dimensions and `\newdimen` registers and prints through `\the`, while `\glueexpr ... \relax` evaluates glue with `plus`/`minus` components over dimensions and `\newskip` registers, with parenthesised sub-expressions allowed and register operands keeping all three components; `\noexpand\token` keeps the token unexpanded for the current pass (a later pass still expands it), and a later `\def` with the same name replaces the earlier definition The LaTeX internals `\@namedef`, `\@nameuse`, `\@ifundefined`, `\@firstofone`, `\@firstoftwo`, `\@secondoftwo` and `\@empty` expand, and `\@ifstar{yes}{no}` / `\@ifnextchar<token>{yes}{no}` choose from the following token, and `@` counts as a letter in control words so `\makeatletter`-guarded names parse `\numexpr` evaluates `+`, `-`, `*`, `/` and parentheses over integers and integer registers, either standalone or after `\the` `\newskip\name` declares a glue register that `\the\name` prints as `wpt plus spt minus hpt`. `\newdimen\name` declares a dimension register whose value `\name=<dimension>`, `\advance\name by <dimension>`, `\multiply\name by <n>` and `\divide\name by <n>` update and which `\the\name` prints in TeX's `pt` form.......`, `\advance\name by ...`, `\multiply\name by ...` and `\divide\name by ...` update and which `\the\name`/`\number\name` print.
Route-D integration can also be checked against a real TeX page: `cargo test -p texrra-tex-core --test route_d` includes `route_d_page_matches_pdftex_raster_geometry`, which renders the route-D PDF and a pdfTeX Letter page at the same scaled-point geometry, rasterizes both with `pdftoppm`, and compares ink line count plus left, right, and bottom edges. It is skipped when `pdflatex`/`pdftoppm` are unavailable. `route_d_multiline_bands_track_pdftex` extends that check to a wrapped paragraph: the pixel rows that carry ink form one band per TeX line, and every band top, bottom, left edge and (except for the last line, whose width follows the break point) right edge must land within a couple of pixels of the pdfTeX page.
Route-D float placement mirrors TeX fractions:
- `Document::top_fraction_percent` defaults to 70 (`\topfraction`); a taller top float keeps body text off its page.
- `Document::bottom_fraction_percent` defaults to 30 (`\bottomfraction`); a bottom float that cannot fit is carried to the next page's bottom while the current page keeps filling, matching TeX's page builder.
- `Document::top_number`, `bottom_number` and `total_number` default to TeX's 2, 1 and 12; they cap top floats, bottom floats and all floats on one page.
- `Document::float_sep` defaults to 12pt (`\floatsep`); stacked top floats or stacked bottom floats reserve that gap between each other, in full layout and after `Engine::edit`.
- `Document::text_float_sep` defaults to 20pt (`\textfloatsep`); a page that carries both floats and body text reserves one such gap between them. `Page::display_list_with_layout(page_goal, text_float_sep)` mirrors that in rendered output, while `display_list_with_goal` keeps the historic no-gap behaviour for callers without document settings.
- A `[t]` float that appears while a page is already filling joins the top of that same page (TeX's `\@toplist`): its height plus `\textfloatsep` is charged to that page, so the body stops earlier; only a page break before the float moves it forward.
- Floats that start a page sit at the top margin: float material does not consume `\topskip`; only body text does.
- `FloatPlacement::Here` keeps an `[h]` float in the body flow: `Document::in_text_sep` (TeX `\intextsep`, default 12pt) separates it from the surrounding text, the float moves to the next page when it does not fit, and it counts against `\totalnumber`. `Page::display_list_with_layout` paints the float at the same flow position the page builder reserved.
- `Engine::edit` applies the float fractions, number limits and separations, so incremental layout matches full layout.
These glyphs are rasterized at
600 dpi and shared by PDF and SVG. Ordinary math atom glyphs are rasterized from
the selected font face at the same resolution, so PDF and SVG paint the same
@@ -433,7 +618,7 @@ the face used to draw each glyph provides it; missing tables and compound
expressions keep the default script placement. PDF and SVG share the resulting
positions. `\\hat`, `\\widehat`, `\\tilde`, `\\widetilde`, `\\overbrace`,
and `\\underbrace` use horizontal MATH variants and assemblies when available,
with the same accent bitmap in both outputs.
with the same accent bitmap in both outputs. Bitmap accents are painted before the base glyph so their opaque background cannot clip the nucleus.
`matrix`, `pmatrix`, `bmatrix`,
`Bmatrix`, `vmatrix`, `Vmatrix`, `cases`, `aligned`, `gathered`, `multline`, and
`array` environments build a two-dimensional math grid. Matrix delimiters are
@@ -477,18 +662,65 @@ document: spacing macros, symbols and letters, NFSS declarations, small caps,
advisory breaks, starred `\vspace`/`\hspace`, `center`, `\hrule`, `\fbox`,
`\mbox`, and `\parbox`.
## New-template compatibility
The SIVP class (`sn-jnl.cls`) loads completely and `sn-article.tex` previews and exports a 14-page PDF; the Huawei E fragment (`projects/e/问题一.tex`) compiles to 16 A4 pages. This required generic TeX conditionals (`\if`, `\ifx`), `\newcount`/`\newdimen`, `\char`, 64-bit dimension scanning, `tabular*`/`tabularx` environments, and the math accent/operator/arrow vocabulary used by both documents. Both are covered by integration tests.
## Capability matrix (current)
| Area | Implemented | Remaining |
| --- | --- | --- |
| Boxes | `\rule`, inline framed `\fbox`, block `\parbox`/`\minipage`, `\vbox`/`\vtop` (as full-width block), inline `\mbox`/`\makebox`, `\raisebox`, `center`, `\hrule` | true nested VBox material |
| Boxes | `\rule`, inline framed `\fbox`, block `\parbox`/`\minipage`, `\vbox`/`\vtop` (vertical material capture), inline `\mbox`/`\makebox`, `\raisebox`, `center`, `\hrule` | independent VBox natural width/baseline |
| Fonts | serif/sans/mono faces, bold/italic/mono/sans declarations, group scoping, true scaled small caps | — |
| Paragraphs | Knuth-Plass breaking, TeX hyphenation, justification, centering, `\parindent` (17pt default), `\hfill`/`\hfil` | `\raggedright`/`\raggedleft` |
| Notes/floats | footnotes with page-bottom insertion area, title/author `\thanks`, figure/table `[htbp]` placement (top/bottom/page/here approximations) | deferred float queue, `\textfraction` |
| Contents | `\tableofcontents`, `\listoffigures`, `\listoftables` generated from numbered headings and captions, page numbers resolved after pagination | dotted leaders, per-chapter book/report contents |
| Paragraphs | Knuth-Plass breaking, TeX hyphenation, justification, `\centering`/`\raggedright`/`\raggedleft`, `\parindent` (17pt default), `\hfill`/`\hfil` | — |
| Notes/floats | footnotes with page-bottom insertion area, title/author `\thanks`, figure `[htbp]` placement (deferred top floats, bottom/page/here), table `[t]`/`[b]`/`[p]` placement | table float-page queues, `\textfraction` |
| Contents | `\tableofcontents`, `\listoffigures`, `\listoftables` generated from numbered headings and captions, dotted leaders, page numbers resolved after pagination | per-chapter book/report contents |
| Pages | A4/Letter/... page sizes, margins/geometry, automatic pagination, `\newpage`, `\pagebreak`, plain/fancy page styles, `\thispagestyle`, fancyhdr L/C/R headers and footers | — |
| Classes/packages | built-in + local classes, option protocol, local package options, base font sizes 10/11/12pt | class-specific section formatting |
| Links | `\href`, `\url`, hyperref-green link text, `\orcidlink{id}` green `iD` badge, clickable PDF `/Annots` URI annotations for visible URLs, `\href` labels, and ORCID author badges | — |
| Classes/packages | built-in + local classes, option protocol, local package options, base font sizes 10/11/12pt, chapter headings and numbering, chapter page breaks, document-level custom `\maketitle`, native arxiv-style preprint title blocks (rules, `\undertitle`, author columns, long date) | class-specific formatting beyond chapter breaks |
| Live preview | incremental paragraph cache, page-hash diffing, SVG refresh | — |
The compatibility layer also covers spacing macros, text symbols/letters, style
commands, break advisories, and document metadata; see the sections above.
PDF-only figures are rendered as placeholders sized from the source PDF page aspect ratio (until native PDF page embedding lands).
Numeric bibliographies render authors as Surname, I. rather than full given names.
## Route D experimental core
`crates/texrra-tex-core` is the start of a TeX-compatible incremental layout
core. It does not embed pdfTeX/XeTeX/Tectonic; it is a new Rust engine designed
around page-boundary checkpoints and page-hash diffing. M0 implements vertical
boxes/glue, a simple page builder, serializable checkpoints and a page-local
edit demo. M1 adds the horizontal box/glue/penalty model, an item-stream Knuth-Plass-style
paragraph builder, CMR10 metrics extracted from `cmr10.tfm`, and a matching pdfTeX line-break fixture. Paragraphs are split at line
boundaries when they cross a page, and the pdfLaTeX oracle covers the
90-240pt measure matrix plus register, `\hangindent`/`\parshape`,
`\parfillskip`, sentence-spacing with custom `\sfcode`,
`\spaceskip`/`\xspaceskip`, `\looseness` and vertical-glue fixtures. Overflowing
insertion material is split at item boundaries, with the tail held over to the
next page. The production v1 engine remains the
default until the new core reaches layout parity. See `docs/TEX_CORE.md`. The complete phased plan (P0 oracle harness, TeX-exact paragraphs,
page builder and `\\output`, `\\halign`, math, Computer Modern fonts, class
execution, service and incrementality targets) is in
[`docs/ROUTE_D_PLAN.md`](docs/ROUTE_D_PLAN.md).
The first M7 service integration is available as `POST /api/route-d/preview`, with PDF export at `POST /api/route-d/pdf`.
It accepts blank-line-separated source with a small `\section`/`\textbf`/`\emph`/display-math/list subset, lays it out with the route-D page
builder, and returns the v1-compatible preview shape plus per-page hashes and
SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures; runs of two or three hyphens become en/em dashes, the breaker follows TeX's `\pretolerance`/`\tolerance`/`\emergencystretch` passes with demerits (falling back to TeX's overfull fill when no feasible break exists), and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. Non-final lines bake their justification into the glue widths, so the PDF and the SVG preview are flush to the measure instead of showing natural spaces; with `\raggedright` (`ParagraphStyle::ragged_right`) lines keep their natural widths and fill greedily, because `\rightskip` carries an infinite `fil`. Interline spacing follows TeX (`\baselineskip` unless `\lineskiplimit` forces `\lineskip`), and `Document::par_skip` adds `\parskip` between paragraph units. `page::PageBuilder` selects page breaks by TeX's badness-plus-penalty cost, including glue setting with TeX orders (normal/`\vfil`/`\vfill`/`\vfilll`), `\topskip` and `Document::max_depth` (`\maxdepth`, with each paragraph's last-line descent exposed as `\pagedepth` and only the part beyond `\maxdepth` added to the page height), and breaks ties toward the later breakpoint (TeX's `<=` update), shipping the least overfull break only when nothing fits; `Engine::layout_paged` exposes it for documents of box/glue/penalty/mark/float/insertion units, expanding each paragraph into one node per line with a zero-width interline breakpoint, and route-D previews and PDFs run through it; insertion classes are placed through the same builder, with per-class limits, held-over material and `Document::split_top_skip` (`\splittopskip`, default 10pt) at the top of each continuation, with `Document::split_max_depth` (`\splitmaxdepth`, `\maxdimen` by default) clamping the first continued box's depth and moving the excess into its height, while `Engine::layout` keeps the scrolling builder as the non-paged fallback; paged layouts replay edits from the edited page, falling back to a full rebuild when insertions or an `\output` routine are present. `Document::output_routine` runs an interpreted `\output` program (`\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum` and `\ifodd` over page registers; `\pageno`, `\outputpenalty`, `\deadcycles`, `\vbadness` (the break's badness) and `\insertpenalties` (insertion items held over) are readable, and each page fragment records the penalty that broke it and how much stretch each glue order carries, so `\pagefilstretch`, `\pagefillstretch` and `\pagefilllstretch` are readable) over those paged fragments, so a routine can drop pages it does not ship, or ship only the pages it wants based on the break penalty or page number. Embedded text fonts are subset per document to the glyphs actually used (retaining glyph IDs and composite components), and each subset carries a ToUnicode CMap covering its used characters. `Document::h_offset` and `v_offset` (`\hoffset`/`\voffset`) shift the exported
page body through `pdf::PageOrigin`, leaving the sheet size unchanged, while
`Document::paper_width`/`paper_height` (`\paperwidth`/`\paperheight`, default US
Letter) set the MediaBox and the preview page box; the route-D endpoints read
leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight` dimension
assignments from the submitted source. Page marks collected by `\mark` are exposed through
`Engine::top_mark`, `first_mark` and `bot_mark` with TeX's carry-forward rules.
`Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page (the paged builder applies the same limits and carries overflow onto dedicated pages), and `InsertionClass::multiplier` applies TeX's `\count<number>` reserve factor; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. `Engine::layout_paged` feeds the same material through `page::PageBuilder`, which places top floats at the head of a page, defers a late float, reserves `Document::text_float_sep` above the body and applies the insertion class limits; bottom floats sit at the page bottom with `Document::float_sep` between them and a `Document::bottom_fraction_percent` cap, while in-text floats flow inline with their `Document::in_text_sep` gaps counted as body height. Vertical glue is set after the break: `Document::ragged_bottom` defaults to TeX's `\raggedbottom`, and setting it false applies `\flushbottom`, stretching `StretchGlue` so the page body reaches the goal; glue of the highest order with stretch absorbs the whole setting, so `\vfil` makes short pages free. `POST /preview` and the project APIs now default to route-D with a v1 fallback; `?engine=v1` (or `TEXRRA_ENGINE=v1`) forces the old pipeline.
Project previews and PDFs default to the new core (`POST /api/projects/{id}/preview` without a query); `?engine=v1` or `TEXRRA_ENGINE=v1` forces the old v1 pipeline. An explicit `?engine=` always wins for both previews and PDFs. The web client exposes this as the `引擎: v1` / `引擎: Route-D` toggle in the preview toolbar; the choice is stored in `localStorage` and switches both the preview request and `POST /api/projects/{id}/pdf`, since the PDF handler honors the same `engine=route-d` query. Route-D project previews keep a session, so an unchanged source reports zero recomputed pages, and route-D PDF exports reuse an eight-entry cache keyed by the expanded source (`X-Texrra-Cache: hit`), and the flat `/api/route-d/preview` and `/api/route-d/pdf` endpoints memoise the last 32 previews and eight PDFs by source hash; text edits and structural edits with an unchanged paragraph prefix rebuild from the first difference through `Engine::relayout_from`, reusing the sealed pages before it, while edits without a reusable prefix fall back to a full layout. `POST /api/route-d/edit/{unit}` applies one paragraph edit to the last route-D
document and returns the same page list plus `changedPages` and
`recomputedPages`, exposing the checkpoint/page-hash diff from the core.
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

+142 -3
View File
@@ -55,6 +55,43 @@ impl Default for PageSize {
}
}
/// Layout style for the document title block.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TitleStyle {
/// The generic article title: title, author, date, no rules.
#[default]
Article,
/// Preprint-style title block with rules, an undertitle, and author columns.
Preprint,
/// Journal-style title block: title, author/affiliation columns, abstract,
/// and keywords.
Journal,
}
/// One author block in a structured front matter.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct AuthorBlock {
pub runs: Vec<Run>,
/// One-based affiliation indices attached to this author.
pub affiliations: Vec<usize>,
pub email: Option<String>,
/// Author marked with `*` (corresponding author).
pub corresponding: bool,
}
/// One numbered affiliation in a structured front matter.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Affiliation {
pub index: usize,
pub runs: Vec<Run>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CitationMetadata {
pub author: String,
pub year: String,
}
#[derive(Clone)]
pub struct Footnote {
pub number: u32,
@@ -64,11 +101,29 @@ pub struct Footnote {
#[derive(Clone)]
pub struct DocumentModel {
pub title: String,
/// Rich title runs, preserving inline emphases such as .
pub title_runs: Vec<Run>,
pub author: String,
pub date: String,
/// Style selected by the document's class/package layer.
pub title_style: TitleStyle,
/// Optional line printed under the title rules, e.g. "A Preprint".
pub undertitle: Option<String>,
/// Short title from `\title[short]{long}`.
pub short_title: Option<String>,
/// Structured author blocks from `\author` / `\affil` / `\email`.
pub authors: Vec<AuthorBlock>,
/// Numbered affiliations from `\affil[n]{...}`.
pub affiliations: Vec<Affiliation>,
/// Body of `\abstract{...}` captured for journal title blocks.
pub abstract_runs: Vec<Run>,
/// Body of `\keywords{...}` captured for journal title blocks.
pub keywords: Vec<Run>,
pub page: PageSize,
pub parindent: common::Scaled,
/// Base font size selected by the document class (10, 11, or 12pt).
/// Number of text columns (1 for article, 2 for `iicol`/`twocolumn`).
pub columns: u8,
pub base_font_size: u8,
pub margins: PageMargins,
pub show_title: bool,
@@ -76,6 +131,14 @@ pub struct DocumentModel {
pub block_sources: Vec<Option<SourceLocation>>,
pub labels: HashMap<String, String>,
pub citations: HashMap<String, usize>,
pub citation_metadata: HashMap<String, CitationMetadata>,
/// Display text -> hyperlink URL for `\href` annotations.
pub link_targets: HashMap<String, String>,
pub orcid_urls: Vec<String>,
/// Bibliography keys in the order their metadata was declared. Needed to
/// assign natbib-style year suffixes (2014a, 2014b, ...) deterministically.
pub bibliography_order: Vec<String>,
pub author_year_citations: bool,
pub footnotes: Vec<Footnote>,
pub page_style: PageStyle,
pub page_style_overrides: Vec<PageStyleOverride>,
@@ -85,18 +148,32 @@ impl Default for DocumentModel {
fn default() -> Self {
Self {
title: String::new(),
title_runs: Vec::new(),
author: String::new(),
date: String::new(),
title_style: TitleStyle::default(),
undertitle: None,
short_title: None,
authors: Vec::new(),
affiliations: Vec::new(),
abstract_runs: Vec::new(),
keywords: Vec::new(),
page: PageSize::default(),
// article's default \parindent for 10/11pt text.
parindent: common::Scaled(17 * 65_536),
base_font_size: 11,
columns: 1,
base_font_size: 10,
margins: PageMargins::default(),
show_title: false,
blocks: Vec::new(),
block_sources: Vec::new(),
labels: HashMap::new(),
citations: HashMap::new(),
citation_metadata: HashMap::new(),
link_targets: HashMap::new(),
orcid_urls: Vec::new(),
bibliography_order: Vec::new(),
author_year_citations: false,
footnotes: Vec::new(),
page_style: PageStyle::default(),
page_style_overrides: Vec::new(),
@@ -167,6 +244,13 @@ pub struct PageStyleOverride {
/// Marker character used by `\thepage` inside header/footer runs; the page
/// renderer substitutes the concrete page number before measuring and painting.
/// Private-use marker for a dotted leader in generated contents lines.
/// Private-use marker toggling hyperlink paint for the following glyphs.
pub const LINK_START_MARKER: char = '\u{F3000}';
pub const LINK_END_MARKER: char = '\u{F3001}';
pub const CONTENTS_LEADER_MARKER: char = '\u{F6000}';
pub const PAGE_NUMBER_MARKER: char = '\u{F5000}';
pub fn page_number_marker_text() -> String {
@@ -212,7 +296,9 @@ pub enum Block {
rows: Vec<Vec<Vec<Run>>>,
caption: Option<Vec<Run>>,
alignments: Vec<ColumnAlignment>,
rules: Vec<usize>,
rules: Vec<TableRule>,
/// Per-cell span and alignment metadata, parallel to `rows`.
cell_styles: Vec<Vec<TableCellStyle>>,
/// Float placement hints from `[htbp]`.
placement: String,
},
@@ -249,13 +335,43 @@ pub enum Block {
PageBreak,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColumnAlignment {
Left,
Center,
Right,
}
/// Per-cell table metadata: a multicolumn span and an optional local alignment.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct TableCellStyle {
pub colspan: usize,
pub alignment: Option<ColumnAlignment>,
}
/// A horizontal table rule. `end_column` is exclusive; `usize::MAX` means the
/// rule spans every column.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TableRule {
pub row: usize,
pub start_column: usize,
pub end_column: usize,
pub trim_left: bool,
pub trim_right: bool,
}
impl TableRule {
pub fn full(row: usize) -> Self {
Self {
row,
start_column: 0,
end_column: usize::MAX,
trim_left: false,
trim_right: false,
}
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct ListBlock {
pub ordered: bool,
@@ -273,6 +389,9 @@ pub struct ListItem {
pub enum UnresolvedReference {
Label(String),
Citation(Vec<String>),
/// A textual citation such as natbib's `\citet`, rendered as
/// `Author (year)` instead of a parenthetical citation.
TextualCitation(Vec<String>),
/// A table-of-contents/list page number for the block with this index.
/// The target is resolved to a page number during page layout.
TocPage(usize),
@@ -312,6 +431,20 @@ pub struct RuleBox {
pub raise: common::Scaled,
/// Thickness of the rule.
pub height: common::Scaled,
/// Optional fill colour; means the regular black rule.
pub color: Option<[u8; 3]>,
pub image: Option<String>,
}
/// Paragraph-level alignment requested by `\raggedright` or `\raggedleft`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ParagraphAlignment {
#[default]
Justified,
RaggedRight,
RaggedLeft,
Centered,
Quote,
}
#[derive(Clone, PartialEq, Eq, Hash)]
@@ -331,8 +464,12 @@ pub struct Run {
pub monospace: bool,
pub sans: bool,
pub small_caps: bool,
/// Hyperlink text (rendered in the hyperref link colour).
pub link: bool,
/// True for the synthetic kern that carries paragraph indentation.
pub paragraph_indent: bool,
/// Alignment declaration active when this run started its paragraph.
pub alignment: Option<ParagraphAlignment>,
}
impl Run {
@@ -353,7 +490,9 @@ impl Run {
monospace: false,
sans: false,
small_caps: false,
link: false,
paragraph_indent: false,
alignment: None,
}
}
}
+522 -31
View File
@@ -4,8 +4,9 @@ use crate::{
TeXGlue, TeXGlueOrder,
document::{
Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, InlineBoxAlign,
ListBlock, ListItem, PageMargins, PageSize, PageStyleOverride, ParsedDocument, RuleBox,
Run, UnresolvedReference,
ListBlock, ListItem, PageMargins, PageSize, PageStyleKind, PageStyleOverride,
ParagraphAlignment, ParsedDocument, RuleBox, Run, TableCellStyle, TableRule, TitleStyle,
UnresolvedReference,
},
expanded,
math_expr::*,
@@ -47,7 +48,10 @@ struct TableBuilder {
cell: Vec<Run>,
caption: Option<Vec<Run>>,
alignments: Vec<ColumnAlignment>,
rules: Vec<usize>,
rules: Vec<TableRule>,
cell_styles: Vec<Vec<TableCellStyle>>,
row_styles: Vec<TableCellStyle>,
pending_cell_style: Option<TableCellStyle>,
}
#[derive(Default)]
@@ -427,6 +431,9 @@ fn contents_kind(block: &Block) -> Option<ContentsKind> {
fn contents_line_runs(title: &[Run], target: usize) -> Vec<Run> {
let mut runs = title.to_vec();
trim_run_end(&mut runs);
runs.push(Run::plain(
crate::document::CONTENTS_LEADER_MARKER.to_string(),
));
let mut filler = Run::plain(String::new());
filler.glue = Some(TeXGlue {
width: common::Scaled::ZERO,
@@ -457,7 +464,9 @@ struct Parser {
text_style_stack: Vec<(expanded::TextStyle, bool, bool, bool, bool, bool)>,
style_declarations: Vec<(usize, expanded::TextStyle)>,
group_depth: usize,
section_numbers: [u32; 3],
link_depth: usize,
section_numbers: [u32; 4],
has_chapters: bool,
equation_number: u32,
figure_number: u32,
table_number: u32,
@@ -469,12 +478,20 @@ struct Parser {
pending_table_caption: Option<Vec<Run>>,
caption_capture: Option<Vec<Run>>,
metadata_capture: Option<(expanded::MetadataField, Vec<Run>)>,
author_affiliations: Vec<usize>,
pending_author_email: Option<String>,
pending_author_corresponding: bool,
email_capture: Option<Vec<Run>>,
affiliation_capture: Option<(usize, Vec<Run>)>,
abstract_capture: Option<Vec<Run>>,
keywords_capture: Option<Vec<Run>>,
framed_box: Option<Vec<Run>>,
box_frame: bool,
box_width: Option<common::Scaled>,
inline_boxes: Vec<InlineBoxSpec>,
minipage: Option<MinipageBuilder>,
footnote_capture: Option<Vec<Run>>,
vbox_stack: Vec<(Vec<Block>, Vec<Option<SourceLocation>>)>,
footnote_counter: u32,
page_decoration_capture: Option<(
bool,
@@ -494,6 +511,59 @@ struct Parser {
paragraph_source: Option<SourceLocation>,
paragraph_indent: Option<common::Scaled>,
suppress_indent: bool,
paragraph_alignment: ParagraphAlignment,
alignment_saves: Vec<ParagraphAlignment>,
in_abstract: bool,
}
fn apply_bibliography_year_suffixes(document: &DocumentModel, items: &mut [(String, Vec<Run>)]) {
for (key, runs) in items {
let Some(metadata) = document.citation_metadata.get(key) else {
continue;
};
if metadata.year.len() != 5 {
continue;
}
let base = &metadata.year[..4];
let suffix = &metadata.year[4..];
if let Some(run) = runs
.iter_mut()
.rev()
.find(|run| run.text.contains(base) && !run.text.contains(&metadata.year))
{
run.text = run.text.replacen(base, &format!("{base}{suffix}"), 1);
}
}
}
fn assign_citation_year_suffixes(document: &mut DocumentModel) {
let mut groups: HashMap<(String, String), Vec<String>> = HashMap::new();
for key in &document.bibliography_order {
let Some(metadata) = document.citation_metadata.get(key) else {
continue;
};
if metadata.author.is_empty() || metadata.year.is_empty() {
continue;
}
groups
.entry((metadata.author.clone(), metadata.year.clone()))
.or_default()
.push(key.clone());
}
for keys in groups.into_values() {
if keys.len() < 2 {
continue;
}
for (index, key) in keys.into_iter().enumerate() {
let Some(metadata) = document.citation_metadata.get_mut(&key) else {
continue;
};
if metadata.year.len() == 4 {
let letter = char::from(b'a' + (index as u8).min(25));
metadata.year.push(letter);
}
}
}
}
impl Parser {
@@ -513,7 +583,9 @@ impl Parser {
text_style_stack: Vec::new(),
style_declarations: Vec::new(),
group_depth: 0,
section_numbers: [0; 3],
link_depth: 0,
section_numbers: [0; 4],
has_chapters: false,
equation_number: 0,
figure_number: 0,
table_number: 0,
@@ -525,12 +597,20 @@ impl Parser {
pending_table_caption: None,
caption_capture: None,
metadata_capture: None,
author_affiliations: Vec::new(),
pending_author_email: None,
pending_author_corresponding: false,
email_capture: None,
affiliation_capture: None,
abstract_capture: None,
keywords_capture: None,
framed_box: None,
box_frame: true,
box_width: None,
inline_boxes: Vec::new(),
minipage: None,
footnote_capture: None,
vbox_stack: Vec::new(),
footnote_counter: 0,
page_decoration_capture: None,
float_placement: String::new(),
@@ -540,6 +620,9 @@ impl Parser {
paragraph_source: None,
paragraph_indent: None,
suppress_indent: false,
paragraph_alignment: ParagraphAlignment::Justified,
alignment_saves: Vec::new(),
in_abstract: false,
}
}
@@ -712,10 +795,24 @@ impl Parser {
self.metadata_capture = Some((active_field, runs));
return;
}
let value = runs.into_iter().map(|run| run.text).collect::<String>();
let value = runs.iter().map(|run| run.text.clone()).collect::<String>();
match field {
expanded::MetadataField::Title => self.document.title = value,
expanded::MetadataField::Author => self.document.author = value,
expanded::MetadataField::Title => {
self.document.title = value;
self.document.title_runs = runs;
}
expanded::MetadataField::Author => {
self.document.author = value;
let affiliations = std::mem::take(&mut self.author_affiliations);
let email = self.pending_author_email.take();
let corresponding = std::mem::take(&mut self.pending_author_corresponding);
self.document.authors.push(crate::document::AuthorBlock {
runs,
affiliations,
email,
corresponding,
});
}
expanded::MetadataField::Date => self.document.date = value,
}
}
@@ -815,7 +912,9 @@ impl Parser {
monospace,
sans,
small_caps,
link: self.link_depth > 0,
paragraph_indent: false,
alignment: None,
};
self.target_runs().push(marker);
}
@@ -857,9 +956,11 @@ impl Parser {
monospace: false,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
link: false,
y_offset: None,
@@ -876,6 +977,22 @@ impl Parser {
self.framed_box = Some(Vec::new());
}
}
expanded::FrontendEventKind::VBoxStart => {
self.flush_paragraph();
let blocks = std::mem::take(&mut self.document.blocks);
let sources = std::mem::take(&mut self.document.block_sources);
self.vbox_stack.push((blocks, sources));
}
expanded::FrontendEventKind::VBoxEnd => {
self.flush_paragraph();
let Some((blocks, sources)) = self.vbox_stack.pop() else {
return;
};
let inner_blocks = std::mem::replace(&mut self.document.blocks, blocks);
let inner_sources = std::mem::replace(&mut self.document.block_sources, sources);
self.document.blocks.extend(inner_blocks);
self.document.block_sources.extend(inner_sources);
}
expanded::FrontendEventKind::ParboxStart { width } => {
self.flush_paragraph();
self.box_frame = false;
@@ -899,14 +1016,117 @@ impl Parser {
self.push_block(Block::FramedBox { runs, frame, width });
}
}
expanded::FrontendEventKind::MetadataValue(field) => {
let value = match field {
expanded::MetadataField::Title => self.document.title.clone(),
expanded::MetadataField::Author => self.document.author.clone(),
expanded::MetadataField::Date => self.document.date.clone(),
};
self.append_text(&value);
}
expanded::FrontendEventKind::MetadataStart(field) => {
self.metadata_capture = Some((*field, Vec::new()));
}
expanded::FrontendEventKind::MetadataEnd(field) => {
self.finish_metadata(*field);
}
expanded::FrontendEventKind::PackageLoaded(package) => {
if package == "sn-jnl" {
self.document.title_style = TitleStyle::Journal;
}
if package == "arxiv" {
self.document.title_style = TitleStyle::Preprint;
self.document.author_year_citations = true;
if self.document.undertitle.is_none() {
self.document.undertitle = Some("A Preprint".to_string());
}
if !self
.document
.page_style_overrides
.iter()
.any(|override_| override_.anchor == 0)
{
self.document.page_style_overrides.push(PageStyleOverride {
anchor: 0,
kind: PageStyleKind::Empty,
});
}
}
}
expanded::FrontendEventKind::MetadataSeparator => {
if self.metadata_capture.is_some() {
self.append_text("\u{F7001}");
}
}
expanded::FrontendEventKind::MetadataShortTitle(short) => {
self.document.short_title = Some(short.clone());
}
expanded::FrontendEventKind::AuthorAffiliations(indices) => {
self.author_affiliations = indices.clone();
}
expanded::FrontendEventKind::MetadataEmailStart => {
self.email_capture = Some(Vec::new());
}
expanded::FrontendEventKind::MetadataAuthorCorresponding => {
self.pending_author_corresponding = true;
}
expanded::FrontendEventKind::MetadataEmailEnd => {
if let Some(mut runs) = self.email_capture.take() {
trim_run_end(&mut runs);
let email = runs.iter().map(|run| run.text.as_str()).collect::<String>();
if let Some(author) = self.document.authors.last_mut() {
author.email = Some(email);
} else {
self.pending_author_email = Some(email);
}
}
}
expanded::FrontendEventKind::AffiliationStart(index) => {
if self.document.title_style == TitleStyle::Article {
self.document.title_style = TitleStyle::Journal;
}
self.affiliation_capture = Some((*index, Vec::new()));
}
expanded::FrontendEventKind::AffiliationEnd => {
if let Some((index, mut runs)) = self.affiliation_capture.take() {
trim_run_end(&mut runs);
self.document
.affiliations
.push(crate::document::Affiliation { index, runs });
}
}
expanded::FrontendEventKind::AbstractStart => {
if self.document.title_style == TitleStyle::Article {
self.document.title_style = TitleStyle::Journal;
}
self.abstract_capture = Some(Vec::new());
}
expanded::FrontendEventKind::AbstractEnd => {
if let Some(mut runs) = self.abstract_capture.take() {
trim_run_end(&mut runs);
self.document.abstract_runs = runs;
}
}
expanded::FrontendEventKind::KeywordsStart => {
if self.document.title_style == TitleStyle::Article {
self.document.title_style = TitleStyle::Journal;
}
self.keywords_capture = Some(Vec::new());
}
expanded::FrontendEventKind::KeywordsEnd => {
if let Some(mut runs) = self.keywords_capture.take() {
trim_run_end(&mut runs);
self.document.keywords = runs;
}
}
expanded::FrontendEventKind::Geometry(settings) => {
apply_class_font_size(&mut self.document, settings);
if settings
.split(",")
.any(|option| matches!(option.trim(), "iicol" | "twocolumn"))
{
self.document.columns = 2;
}
apply_geometry(&mut self.document, settings);
}
expanded::FrontendEventKind::TextStyleStart(style) => self.begin_style(*style),
@@ -1001,7 +1221,13 @@ impl Parser {
expanded::FrontendEventKind::ListOfTables => {
self.push_contents_placeholder(CONTENTS_TABLES_MARKER);
}
expanded::FrontendEventKind::GroupStart => self.group_depth += 1,
expanded::FrontendEventKind::ParagraphAlignment(alignment) => {
self.paragraph_alignment = *alignment;
}
expanded::FrontendEventKind::GroupStart => {
self.group_depth += 1;
self.alignment_saves.push(self.paragraph_alignment);
}
expanded::FrontendEventKind::GroupEnd => {
let depth = self.group_depth;
while self
@@ -1014,25 +1240,73 @@ impl Parser {
}
}
self.group_depth = self.group_depth.saturating_sub(1);
self.paragraph_alignment = self
.alignment_saves
.pop()
.unwrap_or(ParagraphAlignment::Justified);
}
expanded::FrontendEventKind::LiteralAmpersand
| expanded::FrontendEventKind::MathCell => self.append_literal_ampersand(),
expanded::FrontendEventKind::LinkStart => {
self.link_depth = self.link_depth.saturating_add(1);
}
expanded::FrontendEventKind::LinkTarget { text, url } => {
if url.contains("orcid.org") {
self.document.orcid_urls.push(url.clone());
}
self.document.link_targets.insert(text.clone(), url.clone());
}
expanded::FrontendEventKind::LinkEnd => {
self.link_depth = self.link_depth.saturating_sub(1);
}
expanded::FrontendEventKind::LiteralCharacter(character) => {
self.append_text(&character.to_string())
}
expanded::FrontendEventKind::LineBreak => self.append_text(" "),
expanded::FrontendEventKind::LineBreak => {
if self.metadata_capture.is_some() {
self.append_metadata_line_break();
} else {
self.append_text(" ");
}
}
expanded::FrontendEventKind::RowBreak => {
if self.table.is_some() {
self.finish_table_row();
} else if self.metadata_capture.is_some() {
self.append_metadata_line_break();
} else {
self.append_text(" ");
}
}
expanded::FrontendEventKind::ListItem => self.start_list_item(),
expanded::FrontendEventKind::TableCell => self.finish_table_cell(),
expanded::FrontendEventKind::TableCellSpan { colspan, alignment } => {
if let Some(table) = &mut self.table {
table.pending_cell_style = Some(TableCellStyle {
colspan: (*colspan).max(1),
alignment: *alignment,
});
}
}
expanded::FrontendEventKind::TableRule => {
if let Some(table) = &mut self.table {
table.rules.push(table.rows.len());
table.rules.push(TableRule::full(table.rows.len()));
}
}
expanded::FrontendEventKind::TableRuleRange {
start_column,
end_column,
trim_left,
trim_right,
} => {
if let Some(table) = &mut self.table {
table.rules.push(TableRule {
row: table.rows.len(),
start_column: *start_column,
end_column: *end_column,
trim_left: *trim_left,
trim_right: *trim_right,
});
}
}
expanded::FrontendEventKind::DisplayMath {
@@ -1184,13 +1458,32 @@ impl Parser {
self.append_reference(UnresolvedReference::Label(key.clone()))
}
expanded::FrontendEventKind::Citation(keys) => {
self.append_reference(UnresolvedReference::Citation(
keys.split(',').map(str::trim).map(str::to_string).collect(),
))
let (keys, textual) = match keys.strip_prefix("@text:") {
Some(keys) => (keys, true),
None => (keys.as_str(), false),
};
let keys = keys.split(',').map(str::trim).map(str::to_string).collect();
self.append_reference(if textual {
UnresolvedReference::TextualCitation(keys)
} else {
UnresolvedReference::Citation(keys)
})
}
expanded::FrontendEventKind::BibliographyItem(key) => {
self.start_bibliography_item(key.clone())
}
expanded::FrontendEventKind::BibliographyMetadata { key, author, year } => {
if !self.document.bibliography_order.contains(key) {
self.document.bibliography_order.push(key.clone());
}
self.document.citation_metadata.insert(
key.clone(),
crate::document::CitationMetadata {
author: author.clone(),
year: year.clone(),
},
);
}
expanded::FrontendEventKind::IncludeGraphics { options, path } => {
self.add_image(path.clone(), options.clone())
}
@@ -1224,9 +1517,11 @@ impl Parser {
monospace: false,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
link: false,
y_offset: None,
@@ -1237,7 +1532,13 @@ impl Parser {
fn start_heading(&mut self, level: u8, numbered: bool) {
self.flush_paragraph();
self.finish_heading();
let level = level.clamp(1, 3);
let level = level.min(3);
if level == 0 {
self.has_chapters = true;
if !self.document.blocks.is_empty() {
self.push_block(Block::PageBreak);
}
}
let runs = if numbered {
let number = self.next_section_number(level);
self.current_reference = number.clone();
@@ -1285,6 +1586,17 @@ impl Parser {
}
}
fn append_metadata_line_break(&mut self) {
let Some((_, runs)) = &mut self.metadata_capture else {
return;
};
if let Some(last) = runs.last_mut() {
last.text.push('\n');
} else {
runs.push(Run::plain("\n".to_string()));
}
}
fn append_text(&mut self, text: &str) {
if normalize_whitespace(text).is_empty() {
return;
@@ -1303,6 +1615,7 @@ impl Parser {
let monospace = self.monospace;
let sans = self.sans;
let small_caps = self.small_caps;
let link = self.link_depth > 0;
if self.table.is_some() {
let mut pieces = text.split('&').peekable();
while let Some(piece) = pieces.next() {
@@ -1314,6 +1627,7 @@ impl Parser {
monospace,
sans,
small_caps,
link,
);
if pieces.peek().is_some() {
self.finish_table_cell();
@@ -1328,8 +1642,15 @@ impl Parser {
monospace,
sans,
small_caps,
link,
);
}
let alignment = self.paragraph_alignment;
if alignment != ParagraphAlignment::Justified
&& let Some(run) = self.target_runs().last_mut()
{
run.alignment = Some(alignment);
}
}
fn append_kern(&mut self, width: common::Scaled) {
@@ -1366,9 +1687,11 @@ impl Parser {
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
link: false,
y_offset: None,
@@ -1395,6 +1718,8 @@ impl Parser {
width,
raise,
height,
color: None,
image: None,
}),
box_run: None,
unresolved_reference: None,
@@ -1403,9 +1728,11 @@ impl Parser {
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
link: false,
y_offset: None,
@@ -1445,9 +1772,11 @@ impl Parser {
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
link: false,
y_offset: None,
@@ -1497,9 +1826,11 @@ impl Parser {
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
link: false,
y_offset: None,
@@ -1515,6 +1846,31 @@ impl Parser {
.expect("page decoration capture was checked")
.2;
}
if self.email_capture.is_some() {
return self
.email_capture
.as_mut()
.expect("email capture was checked");
}
if self.affiliation_capture.is_some() {
return &mut self
.affiliation_capture
.as_mut()
.expect("affiliation capture was checked")
.1;
}
if self.abstract_capture.is_some() {
return self
.abstract_capture
.as_mut()
.expect("abstract capture was checked");
}
if self.keywords_capture.is_some() {
return self
.keywords_capture
.as_mut()
.expect("keywords capture was checked");
}
if self.footnote_capture.is_some() {
return self
.footnote_capture
@@ -1530,6 +1886,10 @@ impl Parser {
&& self.centered.is_none()
&& self.framed_box.is_none()
&& self.metadata_capture.is_none()
&& self.email_capture.is_none()
&& self.affiliation_capture.is_none()
&& self.abstract_capture.is_none()
&& self.keywords_capture.is_none()
&& self.page_decoration_capture.is_none()
&& self.caption_capture.is_none()
&& self.heading.is_none()
@@ -1594,6 +1954,7 @@ impl Parser {
let monospace = self.monospace;
let sans = self.sans;
let small_caps = self.small_caps;
let link = self.link_depth > 0;
append_run(
self.target_runs(),
"&".to_string(),
@@ -1602,6 +1963,7 @@ impl Parser {
monospace,
sans,
small_caps,
link,
);
}
@@ -1636,9 +1998,11 @@ impl Parser {
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
link: true,
y_offset: None,
@@ -1752,6 +2116,16 @@ impl Parser {
let indent = self.paragraph_indent.take().unwrap_or(common::Scaled::ZERO);
if !self.paragraph.is_empty() {
let mut runs = std::mem::take(&mut self.paragraph);
if self.paragraph_alignment != ParagraphAlignment::Justified
&& let Some(first) = runs.first_mut()
{
first.alignment = Some(self.paragraph_alignment);
} else if self.in_abstract
&& runs.first().is_some_and(|run| run.alignment.is_none())
&& let Some(first) = runs.first_mut()
{
first.alignment = Some(ParagraphAlignment::Quote);
}
prepend_paragraph_indent(&mut runs, indent);
let source = self.paragraph_source.take();
self.push_block_at(Block::Paragraph(runs), source);
@@ -1796,7 +2170,7 @@ impl Parser {
self.flush_paragraph();
self.finish_list();
}
(true, "tabular") => {
(true, "tabular") | (true, "tabular*") | (true, "tabularx") | (true, "longtable") => {
self.flush_paragraph();
self.finish_list();
self.table = Some(TableBuilder {
@@ -1808,7 +2182,10 @@ impl Parser {
self.current_reference = self.table_number.to_string();
}
}
(false, "tabular") => self.finish_table(),
(false, "tabular")
| (false, "tabular*")
| (false, "tabularx")
| (false, "longtable") => self.finish_table(),
(true, "figure") => {
self.flush_paragraph();
self.float_placement = String::new();
@@ -1842,6 +2219,44 @@ impl Parser {
self.table_active = false;
self.current_table_block = None;
}
(true, "abstract") => {
self.flush_paragraph();
let mut heading = Run::plain("Abstract".to_string());
heading.bold = true;
heading.small_caps = true;
self.push_block(Block::Centered {
runs: vec![heading],
});
self.in_abstract = true;
}
(false, "abstract") => {
self.flush_paragraph();
self.in_abstract = false;
}
(true, "raggedright") => {
self.flush_paragraph();
self.alignment_saves.push(self.paragraph_alignment);
self.paragraph_alignment = ParagraphAlignment::RaggedRight;
}
(false, "raggedright") => {
self.flush_paragraph();
self.paragraph_alignment = self
.alignment_saves
.pop()
.unwrap_or(ParagraphAlignment::Justified);
}
(true, "raggedleft") => {
self.flush_paragraph();
self.alignment_saves.push(self.paragraph_alignment);
self.paragraph_alignment = ParagraphAlignment::RaggedLeft;
}
(false, "raggedleft") => {
self.flush_paragraph();
self.paragraph_alignment = self
.alignment_saves
.pop()
.unwrap_or(ParagraphAlignment::Justified);
}
(true, "center") => {
self.flush_paragraph();
if self.centered.is_none() {
@@ -1872,10 +2287,19 @@ impl Parser {
}
fn next_section_number(&mut self, level: u8) -> String {
let index = usize::from(level.saturating_sub(1).min(2));
let index = usize::from(level.min(3));
self.section_numbers[index] += 1;
self.section_numbers[index + 1..].fill(0);
self.section_numbers[..=index]
if level == 0 {
self.has_chapters = true;
return self.section_numbers[0].to_string();
}
let start = if self.has_chapters && self.section_numbers[0] > 0 {
0
} else {
1
};
self.section_numbers[start..=index]
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
@@ -1888,16 +2312,28 @@ impl Parser {
// ORCID icons inside \author) are dropped here.
return;
}
if let Some(table) = &mut self.table {
// Table-cell images reuse the rule box so table layout can keep the
// reference grid; the PDF renderer embeds the source image at this rect.
let width = (0.138_f64 * 160.0 * 72.27 / 25.4 * 65536.0).round() as i32;
let height = (width as f64 * 1.35).round() as i32;
let mut run = Run::plain(String::new());
run.rule = Some(RuleBox {
width: common::Scaled(width),
raise: common::Scaled(0),
height: common::Scaled(height),
color: Some([170, 170, 170]),
image: Some(path.clone()),
});
table.cell.push(run);
return;
}
self.flush_paragraph();
if !self.figure_active {
self.figure_number += 1;
}
self.current_reference = self.figure_number.to_string();
if self.figure_active
&& !self.float_placement.is_empty()
&& !self.float_placement.contains('h')
&& (self.float_placement.contains('t') || self.float_placement.contains('p'))
{
if self.figure_active && self.float_placement.contains('p') {
self.push_block(Block::PageBreak);
}
let index = self.document.blocks.len();
@@ -1958,6 +2394,8 @@ impl Parser {
fn finish_table_cell(&mut self) {
if let Some(table) = &mut self.table {
trim_run_end(&mut table.cell);
let style = table.pending_cell_style.take().unwrap_or_default();
table.row_styles.push(style);
table.row.push(std::mem::take(&mut table.cell));
}
}
@@ -1968,6 +2406,9 @@ impl Parser {
&& !table.row.is_empty()
{
table.rows.push(std::mem::take(&mut table.row));
table
.cell_styles
.push(std::mem::take(&mut table.row_styles));
}
}
@@ -1978,7 +2419,7 @@ impl Parser {
{
if !self.table_placement.is_empty()
&& !self.table_placement.contains('h')
&& (self.table_placement.contains('t') || self.table_placement.contains('p'))
&& self.table_placement.contains('p')
{
self.push_block(Block::PageBreak);
}
@@ -1989,6 +2430,7 @@ impl Parser {
caption,
alignments: table.alignments,
rules: table.rules,
cell_styles: table.cell_styles,
placement: self.table_placement.clone(),
});
if self.table_active {
@@ -2022,9 +2464,11 @@ impl Parser {
fn finish_bibliography(&mut self) {
self.finish_bibliography_item();
if let Some(bibliography) = self.bibliography.take()
assign_citation_year_suffixes(&mut self.document);
if let Some(mut bibliography) = self.bibliography.take()
&& !bibliography.items.is_empty()
{
apply_bibliography_year_suffixes(&self.document, &mut bibliography.items);
self.push_block(Block::Bibliography(bibliography.items));
}
}
@@ -2096,9 +2540,11 @@ fn indent_run(indent: common::Scaled) -> Run {
monospace: false,
sans: false,
small_caps: false,
link: false,
y_offset: None,
footnote_number: None,
paragraph_indent: true,
alignment: None,
}
}
@@ -2142,6 +2588,7 @@ fn append_run(
monospace: bool,
sans: bool,
small_caps: bool,
link: bool,
) {
if text.is_empty() {
return;
@@ -2165,6 +2612,7 @@ fn append_run(
&& last.monospace == monospace
&& last.sans == sans
&& last.small_caps == small_caps
&& last.link == link
{
last.text.push_str(&text);
return;
@@ -2183,7 +2631,9 @@ fn append_run(
monospace,
sans,
small_caps,
link,
paragraph_indent: false,
alignment: None,
y_offset: None,
@@ -2248,10 +2698,29 @@ fn apply_class_font_size(document: &mut DocumentModel, settings: &str) {
/// This is shared by the document parser and by the frontend's live length
/// tracker, so `\textwidth`/`\textheight` expanded during macro processing
/// match the layout that the parser will produce.
fn split_geometry_settings(settings: &str) -> Vec<&str> {
let mut parts = Vec::new();
let mut depth = 0usize;
let mut start = 0usize;
for (index, character) in settings.char_indices() {
match character {
'{' => depth += 1,
'}' => depth = depth.saturating_sub(1),
',' if depth == 0 => {
parts.push(&settings[start..index]);
start = index + 1;
}
_ => {}
}
}
parts.push(&settings[start..]);
parts
}
pub fn apply_geometry_settings(page: &mut PageSize, margins: &mut PageMargins, settings: &str) {
// Paper size first: explicit margins in the same list must be measured
// against the final page dimensions.
for setting in settings.split(',') {
for setting in split_geometry_settings(settings) {
let setting = setting.trim();
if setting.is_empty() {
continue;
@@ -2282,7 +2751,7 @@ pub fn apply_geometry_settings(page: &mut PageSize, margins: &mut PageMargins, s
}
}
for setting in settings.split(',') {
for setting in split_geometry_settings(settings) {
let Some((key, value)) = setting.split_once('=') else {
continue;
};
@@ -2318,14 +2787,36 @@ pub fn apply_geometry_settings(page: &mut PageSize, margins: &mut PageMargins, s
// influences the computed bottom margin in the same settings list.
let page_width = page.width_mm;
let page_height = page.height_mm;
for setting in settings.split(',') {
for setting in split_geometry_settings(settings) {
let Some((key, value)) = setting.split_once('=') else {
continue;
};
let Some(value) = parse_dimension(value.trim()) else {
let key = key.trim();
let value = value.trim();
if key == "text" {
let inner = value
.strip_prefix('{')
.and_then(|value| value.strip_suffix('}'))
.unwrap_or(value);
let Some((width, height)) = inner.split_once(',') else {
continue;
};
let (Some(width), Some(height)) = (
parse_dimension(width.trim()),
parse_dimension(height.trim()),
) else {
continue;
};
let side = ((page_width - width) / 2.0).max(0.0);
margins.left = side;
margins.right = side;
margins.bottom = (page_height - margins.top - height).max(0.0);
continue;
}
let Some(value) = parse_dimension(value) else {
continue;
};
match key.trim() {
match key {
"textwidth" => {
let side = ((page_width - value) / 2.0).max(0.0);
margins.left = side;
+50
View File
@@ -2,6 +2,7 @@ use std::{ops::Range, sync::Arc};
use crate::{
MathClass, MathStyleCommand, TeXGlue,
document::ColumnAlignment,
math_code::UnicodeMathCode,
math_expr::{
MathAccent, MathDelimiterGlyph, MathDelimiterSettings, MathExpr, MathFontFamilies,
@@ -93,6 +94,8 @@ pub enum FrontendEventKind {
ParboxStart {
width: common::Scaled,
},
VBoxStart,
VBoxEnd,
HorizontalRule {
height: common::Scaled,
width: Option<common::Scaled>,
@@ -108,6 +111,7 @@ pub enum FrontendEventKind {
FootnoteStart,
FootnoteEnd,
MetadataStart(MetadataField),
MetadataValue(MetadataField),
MetadataEnd(MetadataField),
DisplayMathStart,
DisplayMathEnd(MathDelimiterSettings),
@@ -216,7 +220,17 @@ pub enum FrontendEventKind {
RowBreak,
ListItem,
TableCell,
TableCellSpan {
colspan: usize,
alignment: Option<ColumnAlignment>,
},
TableRule,
TableRuleRange {
start_column: usize,
end_column: usize,
trim_left: bool,
trim_right: bool,
},
HeadingStart {
level: u8,
numbered: bool,
@@ -234,6 +248,11 @@ pub enum FrontendEventKind {
Reference(String),
Citation(String),
BibliographyItem(String),
BibliographyMetadata {
key: String,
author: String,
year: String,
},
PageStyle(crate::document::PageStyleKind),
ThisPageStyle(crate::document::PageStyleKind),
PageDecorationStart {
@@ -245,6 +264,37 @@ pub enum FrontendEventKind {
header: bool,
},
PageNumber,
/// Start of hyperlink material.
LinkStart,
/// `\href` target: display text and URL, used for PDF annotations.
LinkTarget {
text: String,
url: String,
},
/// End of hyperlink material.
LinkEnd,
/// A package or class was loaded from a local file.
PackageLoaded(String),
/// A separator between author blocks (LaTeX's \And).
MetadataSeparator,
/// Short title from the optional argument of `\title[short]{long}`.
MetadataShortTitle(String),
/// Affiliation indices from the optional argument of `\author[1,2]{...}`.
AuthorAffiliations(Vec<usize>),
/// Start of an `\affil[n]{...}` body.
AffiliationStart(usize),
AffiliationEnd,
/// Start/end of an `\abstract{...}` body captured for the title block.
AbstractStart,
AbstractEnd,
/// Start/end of a `\keywords{...}` body.
KeywordsStart,
KeywordsEnd,
/// Start/end of the e-mail address inside an author block.
MetadataEmailStart,
MetadataAuthorCorresponding,
MetadataEmailEnd,
ParagraphAlignment(crate::document::ParagraphAlignment),
TableOfContents,
ListOfFigures,
ListOfTables,
+74 -21
View File
@@ -1,14 +1,38 @@
use std::collections::HashMap;
use crate::document::{Block, DocumentModel, ListBlock, ParsedDocument, Run, UnresolvedReference};
use crate::document::{
Block, CitationMetadata, DocumentModel, ListBlock, ParsedDocument, Run, UnresolvedReference,
};
/// Resolves document references after parsing has collected all labels and citations.
pub fn resolve(parsed: ParsedDocument) -> DocumentModel {
let mut document = parsed.0;
fn citation_label(
key: &str,
citations: &HashMap<String, usize>,
metadata: &HashMap<String, CitationMetadata>,
author_year: bool,
) -> String {
if author_year && let Some(entry) = metadata.get(key) {
match (entry.author.is_empty(), entry.year.is_empty()) {
(false, false) => return format!("{}, {}", entry.author, entry.year),
(false, true) => return entry.author.clone(),
(true, false) => return entry.year.clone(),
(true, true) => {}
}
}
citations
.get(key)
.map(usize::to_string)
.unwrap_or_else(|| key.to_string())
}
fn resolve_runs(
runs: &mut [Run],
labels: &HashMap<String, String>,
citations: &HashMap<String, usize>,
metadata: &HashMap<String, CitationMetadata>,
author_year: bool,
) {
for run in runs {
let Some(reference) = run.unresolved_reference.take() else {
@@ -24,17 +48,42 @@ pub fn resolve(parsed: ParsedDocument) -> DocumentModel {
.cloned()
.unwrap_or_else(|| "??".to_string()),
UnresolvedReference::Citation(keys) => {
let formatted = keys
.iter()
.map(|key| {
citations
.get(key)
.map(usize::to_string)
.unwrap_or_else(|| key.clone())
})
.collect::<Vec<_>>()
.join(", ");
format!("[{formatted}]")
if author_year {
let formatted = keys
.iter()
.map(|key| citation_label(key, citations, metadata, true))
.collect::<Vec<_>>()
.join("; ");
format!("({formatted})")
} else {
let formatted = keys
.iter()
.map(|key| citation_label(key, citations, metadata, false))
.collect::<Vec<_>>()
.join(", ");
format!("[{formatted}]")
}
}
UnresolvedReference::TextualCitation(keys) => {
if author_year {
keys.iter()
.map(|key| {
let label = citation_label(key, citations, metadata, true);
match label.rsplit_once(", ") {
Some((author, year)) => format!("{author} ({year})"),
None => label,
}
})
.collect::<Vec<_>>()
.join("; ")
} else {
let formatted = keys
.iter()
.map(|key| citation_label(key, citations, metadata, false))
.collect::<Vec<_>>()
.join(", ");
format!("[{formatted}]")
}
}
};
run.text = text;
@@ -45,42 +94,46 @@ pub fn resolve(parsed: ParsedDocument) -> DocumentModel {
list: &mut ListBlock,
labels: &HashMap<String, String>,
citations: &HashMap<String, usize>,
metadata: &HashMap<String, CitationMetadata>,
author_year: bool,
) {
for item in &mut list.items {
resolve_runs(&mut item.runs, labels, citations);
resolve_runs(&mut item.runs, labels, citations, metadata, author_year);
for nested in &mut item.nested {
resolve_list(nested, labels, citations);
resolve_list(nested, labels, citations, metadata, author_year);
}
}
}
let labels = &document.labels;
let citations = &document.citations;
let metadata = &document.citation_metadata;
let author_year = document.author_year_citations;
for block in &mut document.blocks {
match block {
Block::Paragraph(runs) | Block::Heading { runs, .. } => {
resolve_runs(runs, labels, citations)
resolve_runs(runs, labels, citations, metadata, author_year)
}
Block::List(list) => resolve_list(list, labels, citations),
Block::List(list) => resolve_list(list, labels, citations, metadata, author_year),
Block::Table { rows, caption, .. } => {
for cell in rows.iter_mut().flatten() {
resolve_runs(cell, labels, citations);
resolve_runs(cell, labels, citations, metadata, author_year);
}
if let Some(caption) = caption {
resolve_runs(caption, labels, citations);
resolve_runs(caption, labels, citations, metadata, author_year);
}
}
Block::Image { caption, .. } => {
if let Some(caption) = caption {
resolve_runs(caption, labels, citations);
resolve_runs(caption, labels, citations, metadata, author_year);
}
}
Block::FramedBox { runs, .. } | Block::Centered { runs } => {
resolve_runs(runs, labels, citations)
resolve_runs(runs, labels, citations, metadata, author_year)
}
Block::Bibliography(items) => {
for (_, runs) in items {
resolve_runs(runs, labels, citations);
resolve_runs(runs, labels, citations, metadata, author_year);
}
}
Block::HorizontalRule { .. }
+31
View File
@@ -0,0 +1,31 @@
[package]
name = "texrra-tex-core"
version = "0.1.0"
edition = "2024"
license = "MIT OR Apache-2.0"
description = "Experimental incremental TeX-compatible typesetting core (route D)"
[dependencies]
flate2 = "1.1"
hashbrown = { version = "0.17.2", default-features = false, features = ["default-hasher", "raw-entry"] }
harfbuzz_rs = "=3.0.1"
image = { version = "0.23.12", default-features = false, features = ["bmp"] }
lopdf = "0.26"
libloading = "=0.8.9"
md5 = "0.8"
png = "0.18.1"
rusttype = "0.8.3"
read-fonts = { version = "=0.47.0", default-features = false }
rustybuzz = "=0.20.1"
skera = { version = "=0.10.0", default-features = false }
subsetter = { version = "=0.2.3", default-features = false }
unicode-bidi = "=0.3.18"
serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
sha2 = "=0.10.9"
stacker = "=0.1.25"
hyphenate = { path = "../../vendor/hyphenate" }
unicode-normalization = "=0.1.25"
[target.'cfg(all(target_os = "linux", target_env = "gnu"))'.dependencies]
libc = "0.2"
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,14 @@
as-so-ciate
as-so-ciates
dec-li-na-tion
oblig-a-tory
phil-an-thropic
present
presents
project
projects
reci-procity
re-cog-ni-zance
ref-or-ma-tion
ret-ri-bu-tion
ta-ble
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
[["M554 680H33V649H57C134 649 136 638 136 602V78C136 42 134 31 57 31H33V0C68 3 146 3 185 3C226 3 317 3 353 0V31H320C225 31 225 44 225 79V609C225 642 227 649 274 649H377C520 649 541 590 557 455H582Z","M442 698C435 711 433 716 416 716C399 716 397 711 390 698L52 20C47 11 47 9 47 8C47 0 53 0 69 0H763C779 0 785 0 785 8C785 9 785 11 780 20ZM384 616 653 76H114Z","M721 339C721 543 570 705 388 705C209 705 56 545 56 339C56 134 210 -22 388 -22C570 -22 721 137 721 339ZM389 1C290 1 153 87 153 339C153 596 292 683 388 683C489 683 624 592 624 339C624 84 483 1 389 1ZM567 414H542V380H235V414H210V270H235V304H542V270H567Z","M370 695C364 714 358 716 347 716C331 716 329 712 324 695L132 100C122 70 102 31 32 31V0C65 2 116 3 125 3C154 3 207 1 238 0V31C184 32 161 59 161 83C161 88 161 91 166 105L316 571L474 79C479 65 479 63 479 61C479 31 420 31 394 31V0C429 3 500 3 538 3C577 3 622 1 661 0V31C585 31 582 37 570 74Z","M611 677H55L47 521H72C74 562 77 588 84 599C90 607 151 607 160 607H506C517 607 576 607 582 599C589 588 592 562 594 521H619ZM50 0H616L624 167H599C596 121 595 95 587 81C581 70 529 70 507 70H159C141 70 86 70 79 80C71 93 69 123 67 167H42ZM527 438H502V387H164V438H139V266H164V317H502V266H527Z","M613 602C613 638 615 649 692 649H716V680H33V649H57C134 649 136 638 136 602V78C136 42 134 31 57 31H33V0C68 3 142 3 180 3C218 3 293 3 328 0V31H304C227 31 225 42 225 78V649H524V78C524 42 522 31 445 31H421V0C456 3 530 3 568 3C606 3 681 3 716 0V31H692C615 31 613 42 613 78Z","M372 326C381 336 381 340 381 342C381 347 377 352 374 356L169 652H400C569 652 619 616 640 458H665L637 683H82C58 683 56 683 56 660L305 298L67 27C57 16 57 14 57 11C57 0 67 0 82 0H637L665 236H640C622 69 554 42 397 42H121Z","M433 351C433 446 459 628 591 628C622 628 683 613 690 551C691 542 692 535 705 535C721 535 721 544 721 552C721 612 681 705 590 705C486 705 413 614 389 462H388C381 505 346 705 187 705C96 705 56 612 56 552C56 544 56 535 72 535C86 535 86 543 87 548C95 628 181 628 186 628C324 628 344 431 344 351V79C344 45 344 31 249 31H216V0C252 3 347 3 388 3C429 3 525 3 561 0V31H528C433 31 433 44 433 79Z","M399 135C554 147 665 240 665 341C665 445 551 536 399 548V604C399 638 399 652 494 652H527V683C491 680 399 680 358 680C317 680 224 680 188 683V652H221C316 652 316 639 316 604V548C163 533 56 441 56 342C56 239 167 150 316 135V79C316 45 316 31 221 31H188V0C224 3 316 3 357 3C398 3 491 3 527 0V31H494C399 31 399 44 399 79ZM316 158C174 177 156 279 156 341C156 393 166 505 316 525ZM399 526C537 510 565 418 565 342C565 282 550 175 399 157Z","M427 604C427 638 427 652 522 652H555V683C519 680 427 680 386 680C345 680 252 680 216 683V652H249C344 652 344 639 344 604V160C213 195 208 349 208 414C207 535 163 554 119 554H82C67 554 57 554 57 543C57 538 60 533 66 532C99 528 124 514 125 396C125 373 128 294 176 227C215 173 276 144 344 135V79C344 45 344 31 249 31H216V0C252 3 344 3 385 3C426 3 519 3 555 0V31H522C427 31 427 44 427 79V135C499 144 560 174 599 226C651 297 652 376 652 420C652 436 653 525 707 532C713 533 720 534 720 543C720 554 712 554 696 554H658C619 554 570 547 569 402C568 292 535 186 427 160Z","M677 162H652C647 136 643 113 634 89C629 73 626 65 568 65H488C501 121 532 169 577 235C624 306 665 375 665 454C665 593 530 705 361 705C189 705 56 591 56 454C56 375 97 306 144 235C188 169 220 121 233 65H153C95 65 92 73 87 88C79 111 74 137 69 162H44L77 0H237C259 0 262 0 262 21C262 91 231 179 208 243C187 301 159 380 159 455C159 615 269 683 360 683C456 683 562 611 562 455C562 380 535 304 506 222C491 180 459 90 459 21C459 0 462 0 485 0H644Z","M448 400H563V431H445V547C445 636 493 683 538 683C541 683 556 683 571 676C559 672 541 659 541 634C541 611 557 591 584 591C613 591 628 611 628 635C628 671 593 705 537 705C478 705 434 667 429 663C400 700 344 705 317 705C222 705 106 653 106 545V431H27V400H106V76C106 31 95 31 28 31V0C61 1 114 3 139 3C164 3 213 1 250 0V31C183 31 172 31 172 76V400H382V76C382 31 371 31 304 31V0C343 1 390 3 418 3C458 3 505 3 545 0V31H524C450 31 448 42 448 78ZM169 431V544C169 641 251 683 316 683C365 683 393 664 394 664V663C377 661 357 648 357 620C357 614 358 589 385 580C382 567 382 558 382 546V431Z","M330 400C376 400 383 387 383 346V76C383 31 372 31 305 31V0C338 1 391 3 416 3C441 3 490 1 527 0V31C460 31 449 31 449 76V443L323 434C307 433 306 432 305 432C303 431 301 431 287 431H169V544C169 643 255 683 317 683C347 683 383 673 403 650C362 648 356 620 356 604C356 571 382 558 401 558C424 558 447 574 447 604C447 663 392 705 318 705C225 705 106 654 106 545V431H27V400H106V76C106 31 95 31 28 31V0C61 1 114 3 139 3C164 3 213 1 250 0V31C183 31 172 31 172 76V400Z","M383 400V76C383 31 372 31 305 31V0C338 1 391 3 416 3C441 3 490 1 527 0V31C460 31 449 31 449 76V694L413 688C409 688 408 689 404 691C372 705 331 705 320 705C215 705 106 649 106 545V431H27V400H106V76C106 31 95 31 28 31V0C61 1 114 3 139 3C164 3 213 1 250 0V31C183 31 172 31 172 76V400ZM383 431H169V544C169 637 245 683 319 683C328 683 355 683 383 674C374 670 358 660 358 634C358 616 366 601 383 595Z","M607 400C653 400 660 387 660 346V76C660 31 649 31 582 31Line truncated
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+37
View File
@@ -0,0 +1,37 @@
//! M0 demo: a three-paragraph article whose middle paragraph is edited.
//!
//! Run with `cargo run -p texrra-tex-core --example incremental_article`.
//! It prints the page count before/after the edit and the pages that the
//! checkpoint replay had to rebuild.
use texrra_tex_core::{Document, Engine, ParagraphStyle, Unit};
fn paragraph(id: u64, marker: &str) -> Unit {
// Roughly one page of 10pt text at a 300pt page goal.
let text = format!("{} {}", marker, "alpha beta gamma delta ".repeat(80));
Unit::paragraph_with_style(id, text, ParagraphStyle::default())
}
fn main() {
let document = Document::new(
300,
vec![
paragraph(1, "ONE"),
paragraph(2, "TWO"),
paragraph(3, "THREE"),
],
);
let mut engine = Engine::layout(&document);
println!(
"initial: pages={} changed={:?}",
engine.pages().len(),
engine.changed_pages()
);
engine.edit(&document, 2, "TWO edited beta gamma delta ".repeat(60));
println!(
"after edit: pages={} changed={:?}",
engine.pages().len(),
engine.changed_pages()
);
}
+66
View File
@@ -0,0 +1,66 @@
//! Emit a small route-D PDF with text, a rule, an image XObject, and a link.
//!
//! Run with `cargo run -p texrra-tex-core --example pdf_display > /tmp/route-d.pdf`.
use texrra_tex_core::render::{DisplayItem, DisplayList, FontFace, PdfImage};
fn main() {
let mut list = DisplayList {
width: 612 * 65_536,
height: 792 * 65_536,
items: Vec::new(),
images: Vec::new(),
magnification: 1000,
..Default::default()
};
list.push(DisplayItem::Text {
x: 100 * 65_536,
y: 140 * 65_536,
size: 12 * 65_536,
text: "bold face".to_owned(),
font: FontFace::Bold,
});
list.push(DisplayItem::Text {
x: 220 * 65_536,
y: 140 * 65_536,
size: 12 * 65_536,
text: "italic face".to_owned(),
font: FontFace::Italic,
});
list.push(DisplayItem::Text {
x: 72 * 65_536,
y: 100 * 65_536,
size: 12 * 65_536,
text: "route-D XObject".to_string(),
font: texrra_tex_core::render::FontFace::Roman,
});
list.push(DisplayItem::Rule {
x: 72 * 65_536,
y: 120 * 65_536,
width: 200 * 65_536,
height: 2 * 65_536,
});
let index = list.add_image(PdfImage {
width: 2,
height: 2,
rgb: vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0],
});
list.push(DisplayItem::Image {
x: 72 * 65_536,
y: 150 * 65_536,
width: 40 * 65_536,
height: 40 * 65_536,
index,
});
list.link(
72 * 65_536,
220 * 65_536,
120 * 65_536,
12 * 65_536,
"https://example.com/route-d",
);
let pdf = texrra_tex_core::pdf::display_list_to_pdf(&list, 792 * 65_536);
use std::io::Write;
std::io::stdout().write_all(&pdf).expect("write pdf");
}
+117
View File
@@ -0,0 +1,117 @@
//! Project-owned generated files. Ownership is established by actual writes,
//! independent of file names/extensions; content versions remain real inputs.
use crate::resources::ResourceVersion;
use sha2::{Digest, Sha256};
use std::{
collections::BTreeSet,
fs::File,
io::{self, Read},
path::{Path, PathBuf},
};
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GeneratedArtifact {
pub producer: PathBuf,
/// Last recorded output version, not a promise that external tools haven't edited it.
pub version: ResourceVersion,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ArtifactLedger {
schema: u32,
root: PathBuf,
records: Vec<GeneratedArtifact>,
}
impl ArtifactLedger {
pub fn storage_key(root: &Path) -> Result<String, String> {
if !root.is_absolute() {
return Err("artifact project root must be absolute".into());
}
Ok(format!(
"{:x}",
Sha256::digest(serde_json::to_vec(root).map_err(|e| e.to_string())?)
))
}
pub fn new(root: PathBuf) -> Self {
Self {
schema: 1,
root,
records: Vec::new(),
}
}
pub fn decode(bytes: &[u8], root: &Path) -> Result<Self, String> {
let ledger: Self = serde_json::from_slice(bytes)
.map_err(|e| format!("invalid generated-file ledger: {e}"))?;
ledger.validate(root)?;
Ok(ledger)
}
fn validate(&self, root: &Path) -> Result<(), String> {
let mut paths = BTreeSet::new();
if self.schema != 1
|| self.root != root
|| !self.root.is_absolute()
|| self.records.iter().any(|r| {
!r.producer.is_absolute()
|| !r.version.path.is_absolute()
|| !paths.insert(&r.version.path)
|| r.version.sha256.len() != 64
|| !r.version.sha256.bytes().all(|c| c.is_ascii_hexdigit())
})
{
return Err("incompatible generated-file ledger identity or versions".into());
}
Ok(())
}
pub fn encode(&self) -> Result<Vec<u8>, String> {
self.validate(&self.root)?;
serde_json::to_vec_pretty(self).map_err(|e| e.to_string())
}
pub fn owns(&self, path: &Path) -> bool {
self.records.iter().any(|r| r.version.path == path)
}
pub fn paths(&self) -> impl Iterator<Item = &Path> {
self.records.iter().map(|r| r.version.path.as_path())
}
pub fn record(&mut self, producer: &Path, version: ResourceVersion) {
self.forget(&version.path);
self.records.push(GeneratedArtifact {
producer: producer.to_owned(),
version,
});
self.records
.sort_by(|a, b| a.version.path.cmp(&b.version.path));
}
pub fn forget(&mut self, path: &Path) {
self.records.retain(|r| r.version.path != path);
}
}
/// Policy/version inspection, separate from TeX's semantic input and stream reads.
pub fn file_version(path: &Path) -> Result<Option<ResourceVersion>, String> {
let mut file = match File::open(path) {
Ok(file) => file,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(format!("generated-file version {}: {e}", path.display())),
};
let mut hash = Sha256::new();
let mut buffer = [0; 16384];
let mut bytes = 0;
loop {
let count = file
.read(&mut buffer)
.map_err(|e| format!("generated-file version {}: {e}", path.display()))?;
if count == 0 {
break;
}
hash.update(&buffer[..count]);
bytes += count as u64;
}
Ok(Some(ResourceVersion {
path: path.to_owned(),
sha256: format!("{:x}", hash.finalize()),
bytes,
}))
}
+855
View File
@@ -0,0 +1,855 @@
//! Computer Modern 10pt metrics backed by the real TFM files.
use std::sync::OnceLock;
use crate::paragraph::ParagraphFont;
use crate::tfm::TfmMetrics;
/// One Computer Modern text face at 10pt.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Cmr10Metrics {
#[default]
Roman,
Bold,
Italic,
BoldItalic,
Mono,
Sans,
SansBold,
SansItalic,
/// Roman small caps (cmcsc10).
SmallCaps,
/// Roman slanted (cmsl10).
Slanted,
/// Bold extended slanted (cmbxsl10).
BoldSlanted,
/// Italic typewriter (cmitt10).
MonoItalic,
/// Calligraphic capitals from cmsy10 (`\mathcal`).
MathCalligraphic,
/// Blackboard-bold capitals from msbm10 (`\mathbb`).
MathBlackboard,
/// Euler Fraktur letters from eufm10 (`\mathfrak`).
MathFraktur,
/// Math face: italic letters from cmmi10, big operators from cmex10.
Math,
/// Times Roman text metrics (`ptmr8t.tfm`).
TimesRoman,
/// Times bold text metrics (`ptmb8t.tfm`).
TimesBold,
/// Times italic text metrics (`ptmri8t.tfm`).
TimesItalic,
/// Times bold italic text metrics (`ptmbi8t.tfm`).
TimesBoldItalic,
}
static CMR10_TFM: &[u8] = include_bytes!("../assets/cmr10.tfm");
static CMBX10_TFM: &[u8] = include_bytes!("../assets/cmbx10.tfm");
static CMTI10_TFM: &[u8] = include_bytes!("../assets/cmti10.tfm");
static CMBXTI10_TFM: &[u8] = include_bytes!("../assets/cmbxti10.tfm");
static CMTT10_TFM: &[u8] = include_bytes!("../assets/cmtt10.tfm");
static CMSS10_TFM: &[u8] = include_bytes!("../assets/cmss10.tfm");
static CMSSBX10_TFM: &[u8] = include_bytes!("../assets/cmssbx10.tfm");
static CMSSI10_TFM: &[u8] = include_bytes!("../assets/cmssi10.tfm");
static CMCSC10_TFM: &[u8] = include_bytes!("../assets/cmcsc10.tfm");
static CMSL10_TFM: &[u8] = include_bytes!("../assets/cmsl10.tfm");
static CMBXSL10_TFM: &[u8] = include_bytes!("../assets/cmbxsl10.tfm");
static CMITT10_TFM: &[u8] = include_bytes!("../assets/cmitt10.tfm");
static CMMI10_TFM: &[u8] = include_bytes!("../assets/cmmi10.tfm");
static CMEX10_TFM: &[u8] = include_bytes!("../assets/cmex10.tfm");
static CMSY10_TFM: &[u8] = include_bytes!("../assets/cmsy10.tfm");
static MSBM10_TFM: &[u8] = include_bytes!("../assets/msbm10.tfm");
static EUFM10_TFM: &[u8] = include_bytes!("../assets/eufm10.tfm");
static PTMR8T_TFM: &[u8] = include_bytes!("../assets/ptmr8t.tfm");
static PTMB8T_TFM: &[u8] = include_bytes!("../assets/ptmb8t.tfm");
static PTMRI8T_TFM: &[u8] = include_bytes!("../assets/ptmri8t.tfm");
static PTMBI8T_TFM: &[u8] = include_bytes!("../assets/ptmbi8t.tfm");
static CMR10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMBX10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMTI10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMBXTI10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMTT10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMSS10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMSSBX10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMSSI10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMCSC10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMSL10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMBXSL10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMITT10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMMI10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMEX10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static CMSY10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static MSBM10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static EUFM10_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static PTMR8T_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static PTMB8T_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static PTMRI8T_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
static PTMBI8T_METRICS: OnceLock<TfmMetrics> = OnceLock::new();
fn parse(bytes: &[u8]) -> TfmMetrics {
TfmMetrics::parse(bytes).expect("embedded TFM must be valid")
}
fn parse_roman() -> TfmMetrics {
parse(CMR10_TFM)
}
fn parse_bold() -> TfmMetrics {
parse(CMBX10_TFM)
}
fn parse_italic() -> TfmMetrics {
parse(CMTI10_TFM)
}
fn parse_bold_italic() -> TfmMetrics {
parse(CMBXTI10_TFM)
}
fn parse_mono() -> TfmMetrics {
parse(CMTT10_TFM)
}
fn parse_sans() -> TfmMetrics {
parse(CMSS10_TFM)
}
fn parse_sans_bold() -> TfmMetrics {
parse(CMSSBX10_TFM)
}
fn parse_sans_italic() -> TfmMetrics {
parse(CMSSI10_TFM)
}
fn parse_small_caps() -> TfmMetrics {
parse(CMCSC10_TFM)
}
fn parse_slanted() -> TfmMetrics {
parse(CMSL10_TFM)
}
fn parse_bold_slanted() -> TfmMetrics {
parse(CMBXSL10_TFM)
}
fn parse_mono_italic() -> TfmMetrics {
parse(CMITT10_TFM)
}
fn parse_math_italic() -> TfmMetrics {
parse(CMMI10_TFM)
}
fn parse_math_extension() -> TfmMetrics {
parse(CMEX10_TFM)
}
fn parse_math_symbol() -> TfmMetrics {
parse(CMSY10_TFM)
}
fn math_italic_metrics() -> &'static TfmMetrics {
CMMI10_METRICS.get_or_init(parse_math_italic)
}
fn math_extension_metrics() -> &'static TfmMetrics {
CMEX10_METRICS.get_or_init(parse_math_extension)
}
fn math_symbol_metrics() -> &'static TfmMetrics {
CMSY10_METRICS.get_or_init(parse_math_symbol)
}
fn parse_blackboard() -> TfmMetrics {
parse(MSBM10_TFM)
}
fn math_blackboard_metrics() -> &'static TfmMetrics {
MSBM10_METRICS.get_or_init(parse_blackboard)
}
fn parse_fraktur() -> TfmMetrics {
parse(EUFM10_TFM)
}
fn parse_times_roman() -> TfmMetrics {
parse(PTMR8T_TFM)
}
fn parse_times_bold() -> TfmMetrics {
parse(PTMB8T_TFM)
}
fn parse_times_italic() -> TfmMetrics {
parse(PTMRI8T_TFM)
}
fn parse_times_bold_italic() -> TfmMetrics {
parse(PTMBI8T_TFM)
}
fn math_fraktur_metrics() -> &'static TfmMetrics {
EUFM10_METRICS.get_or_init(parse_fraktur)
}
fn metrics_for(font: Cmr10Metrics) -> &'static TfmMetrics {
match font {
Cmr10Metrics::Roman => CMR10_METRICS.get_or_init(parse_roman),
Cmr10Metrics::Bold => CMBX10_METRICS.get_or_init(parse_bold),
Cmr10Metrics::Italic => CMTI10_METRICS.get_or_init(parse_italic),
Cmr10Metrics::BoldItalic => CMBXTI10_METRICS.get_or_init(parse_bold_italic),
Cmr10Metrics::Mono => CMTT10_METRICS.get_or_init(parse_mono),
Cmr10Metrics::Sans => CMSS10_METRICS.get_or_init(parse_sans),
Cmr10Metrics::SansBold => CMSSBX10_METRICS.get_or_init(parse_sans_bold),
Cmr10Metrics::SansItalic => CMSSI10_METRICS.get_or_init(parse_sans_italic),
Cmr10Metrics::SmallCaps => CMCSC10_METRICS.get_or_init(parse_small_caps),
Cmr10Metrics::Slanted => CMSL10_METRICS.get_or_init(parse_slanted),
Cmr10Metrics::BoldSlanted => CMBXSL10_METRICS.get_or_init(parse_bold_slanted),
Cmr10Metrics::MonoItalic => CMITT10_METRICS.get_or_init(parse_mono_italic),
Cmr10Metrics::Math => CMR10_METRICS.get_or_init(parse_roman),
Cmr10Metrics::MathCalligraphic => CMSY10_METRICS.get_or_init(parse_math_symbol),
Cmr10Metrics::MathBlackboard => MSBM10_METRICS.get_or_init(parse_blackboard),
Cmr10Metrics::MathFraktur => EUFM10_METRICS.get_or_init(parse_fraktur),
Cmr10Metrics::TimesRoman => PTMR8T_METRICS.get_or_init(parse_times_roman),
Cmr10Metrics::TimesBold => PTMB8T_METRICS.get_or_init(parse_times_bold),
Cmr10Metrics::TimesItalic => PTMRI8T_METRICS.get_or_init(parse_times_italic),
Cmr10Metrics::TimesBoldItalic => PTMBI8T_METRICS.get_or_init(parse_times_bold_italic),
}
}
impl Cmr10Metrics {
pub const fn new() -> Self {
Self::Roman
}
/// Select the Computer Modern face that corresponds to a paragraph face.
pub const fn for_paragraph_font(font: ParagraphFont) -> Self {
match font {
ParagraphFont::Roman => Self::Roman,
ParagraphFont::Bold => Self::Bold,
ParagraphFont::Italic => Self::Italic,
ParagraphFont::BoldItalic => Self::BoldItalic,
ParagraphFont::Mono => Self::Mono,
ParagraphFont::Sans => Self::Sans,
ParagraphFont::SansBold => Self::SansBold,
ParagraphFont::SansItalic => Self::SansItalic,
ParagraphFont::SmallCaps => Self::SmallCaps,
ParagraphFont::Slanted => Self::Slanted,
ParagraphFont::BoldSlanted => Self::BoldSlanted,
ParagraphFont::MonoItalic => Self::MonoItalic,
ParagraphFont::TimesRoman => Self::TimesRoman,
ParagraphFont::TimesBold => Self::TimesBold,
ParagraphFont::TimesItalic => Self::TimesItalic,
ParagraphFont::TimesBoldItalic => Self::TimesBoldItalic,
}
}
/// Select the face by PDF slot: Roman, bold, italic, bold-italic, mono, sans.
pub const fn for_pdf_slot(slot: usize) -> Self {
match slot {
1 => Self::Bold,
2 => Self::Italic,
3 => Self::BoldItalic,
4 => Self::Mono,
5 => Self::Sans,
6 => Self::Math,
7 => Self::Math,
8 => Self::Math,
9 => Self::MathBlackboard,
10 => Self::MathFraktur,
11 => Self::SansBold,
12 => Self::SansItalic,
13 => Self::SmallCaps,
14 => Self::Slanted,
15 => Self::BoldSlanted,
16 => Self::MonoItalic,
_ => Self::Roman,
}
}
fn metrics(self) -> &'static TfmMetrics {
metrics_for(self)
}
/// Exact embedded TFM metrics for native text. No missing-glyph fallback.
pub fn native_text_metrics(self, character: char) -> Option<(i64, i64, i64, i64)> {
let slot = match character {
'Γ' => '\0',
'ff' => '\u{b}',
'fi' => '\u{c}',
'fl' => '\u{d}',
'ffi' => '\u{e}',
'ffl' => '\u{f}',
c if c.is_ascii() => c,
_ => return None,
};
let f = self.metrics();
if f.char_info(slot)?.width_index == 0 {
return None;
}
Some((f.width(slot), f.height(slot), f.depth(slot), f.italic(slot)))
}
pub fn width(&self, character: char) -> i64 {
if matches!(
*self,
Self::MathCalligraphic | Self::MathBlackboard | Self::MathFraktur
) {
let capital_only = *self != Self::MathFraktur;
if character.is_ascii_uppercase() || (!capital_only && character.is_ascii_lowercase()) {
return self.metrics().width(character);
}
return Self::Math.width(character);
}
if self.is_math() && character.is_ascii_alphabetic() {
let width = math_italic_metrics().width(character);
if width > 0 {
return width;
}
}
if self.is_math() {
if let Some(slot) = math_symbol_slot(character) {
let width = math_symbol_metrics().width(char::from(slot));
if width > 0 {
return width;
}
}
if let Some(slot) = math_extension_slot(character) {
let width = math_extension_metrics().width(char::from(slot));
if width > 0 {
return width;
}
}
}
let width = self.metrics().width(character);
if width > 0 { width } else { 327_680 }
}
/// TeX's ex unit is fontdimen5, which can differ from the ink height of x.
pub fn x_height(&self) -> i64 {
self.metrics().x_height()
}
pub fn height(&self, character: char) -> i64 {
if matches!(
*self,
Self::MathCalligraphic | Self::MathBlackboard | Self::MathFraktur
) {
let capital_only = *self != Self::MathFraktur;
if character.is_ascii_uppercase() || (!capital_only && character.is_ascii_lowercase()) {
return self.metrics().height(character);
}
return Self::Math.height(character);
}
if self.is_math() && character.is_ascii_alphabetic() {
let height = math_italic_metrics().height(character);
if height > 0 {
return height;
}
}
if self.is_math() {
if let Some(slot) = math_symbol_slot(character) {
return math_symbol_metrics().height(char::from(slot));
}
if let Some(slot) = math_extension_slot(character) {
return math_extension_metrics().height(char::from(slot));
}
}
self.metrics().height(character)
}
pub fn depth(&self, character: char) -> i64 {
if matches!(
*self,
Self::MathCalligraphic | Self::MathBlackboard | Self::MathFraktur
) {
let capital_only = *self != Self::MathFraktur;
if character.is_ascii_uppercase() || (!capital_only && character.is_ascii_lowercase()) {
return self.metrics().depth(character);
}
return Self::Math.depth(character);
}
if self.is_math() && character.is_ascii_alphabetic() {
let depth = math_italic_metrics().depth(character);
if depth > 0 {
return depth;
}
}
if self.is_math() {
if let Some(slot) = math_symbol_slot(character) {
return math_symbol_metrics().depth(char::from(slot));
}
if let Some(slot) = math_extension_slot(character) {
return math_extension_metrics().depth(char::from(slot));
}
}
self.metrics().depth(character)
}
pub fn italic(&self, character: char) -> i64 {
if matches!(
*self,
Self::MathCalligraphic | Self::MathBlackboard | Self::MathFraktur
) {
let capital_only = *self != Self::MathFraktur;
if character.is_ascii_uppercase() || (!capital_only && character.is_ascii_lowercase()) {
return self.metrics().italic(character);
}
return Self::Math.italic(character);
}
if self.is_math() && character.is_ascii_alphabetic() {
return math_italic_metrics().italic(character);
}
if self.is_math() {
if let Some(slot) = math_symbol_slot(character) {
return math_symbol_metrics().italic(char::from(slot));
}
if let Some(slot) = math_extension_slot(character) {
return math_extension_metrics().italic(char::from(slot));
}
}
self.metrics().italic(character)
}
pub fn ligature(&self, left: char, right: char) -> Option<(char, char)> {
let slot = self.metrics().ligature_slot(left, right)?;
let unicode = match slot {
11 => 'ff',
12 => 'fi',
13 => 'fl',
14 => 'ffi',
15 => 'ffl',
_ => return None,
};
Some((unicode, char::from(slot)))
}
pub fn kern(&self, left: char, right: char) -> i64 {
self.metrics().kern(left, right)
}
pub fn space(&self) -> i64 {
self.metrics().space()
}
pub fn stretch(&self) -> i64 {
self.metrics().stretch()
}
pub fn shrink(&self) -> i64 {
self.metrics().shrink()
}
pub fn extra_space(&self) -> i64 {
self.metrics().extra_space()
}
}
/// Whether this face is the math face.
impl Cmr10Metrics {
pub const fn is_math(self) -> bool {
matches!(self, Self::Math)
}
}
/// Metrics for a named Computer Modern extension big operator (`\sum` and friends).
pub fn cmex_operator(name: &str) -> Option<(i64, i64, i64)> {
let slot = match name {
"sum" => 80,
"prod" => 81,
"coprod" => 96,
"int" => 82,
"oint" => 72,
"bigcap" => 84,
"bigcup" => 83,
"bigsqcup" => 85,
"bigvee" => 87,
"bigwedge" => 86,
"bigodot" => 74,
"bigotimes" => 78,
"bigoplus" => 76,
"biguplus" => 85,
_ => return None,
};
let metrics = math_extension_metrics();
let width = metrics.width(char::from(slot));
if width == 0 {
return None;
}
Some((
width,
metrics.height(char::from(slot)),
metrics.depth(char::from(slot)),
))
}
/// Map a Unicode n-ary operator to its slot in the bundled cmex10 font.
pub fn math_extension_slot(character: char) -> Option<u8> {
let slot = match character {
'\u{2211}' => 80, // \sum
'\u{220F}' => 81, // \prod
'\u{2210}' => 96, // \coprod
'\u{222B}' => 82, // \int
'\u{222E}' => 72, // \oint
'\u{22C2}' => 84, // \bigcap
'\u{22C3}' => 83, // \bigcup
'\u{2A06}' => 85, // \bigsqcup
'\u{22C1}' => 87, // \bigvee
'\u{22C0}' => 86, // \bigwedge
'\u{2A00}' => 74, // \bigodot
'\u{2A02}' => 78, // \bigotimes
'\u{2A01}' => 76, // \bigoplus
_ => return None,
};
Some(slot)
}
/// Advance width of a `cmsy10` glyph addressed by a Unicode math character.
pub fn math_symbol_width(character: char) -> Option<i64> {
if character.is_ascii_uppercase() {
let width = math_symbol_metrics().width(character);
if width > 0 {
return Some(width);
}
}
math_symbol_slot(character)
.map(|slot| math_symbol_metrics().width(char::from(slot)))
.filter(|width| *width > 0)
}
/// Advance width of a `msbm10` blackboard-bold capital.
pub fn math_blackboard_width(character: char) -> Option<i64> {
if character.is_ascii_uppercase() {
let width = math_blackboard_metrics().width(character);
if width > 0 {
return Some(width);
}
}
None
}
/// Advance width of an `eufm10` Fraktur letter.
pub fn math_fraktur_width(character: char) -> Option<i64> {
if character.is_ascii_alphabetic() {
let width = math_fraktur_metrics().width(character);
if width > 0 {
return Some(width);
}
}
None
}
/// Advance width of a `cmex10` glyph addressed by a Unicode n-ary operator.
pub fn math_extension_width(character: char) -> Option<i64> {
math_extension_slot(character)
.map(|slot| math_extension_metrics().width(char::from(slot)))
.filter(|width| *width > 0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_cmr10_widths() {
let font = Cmr10Metrics::new();
assert!(font.width('A') > 450_000);
assert!((font.width('a') - 327_681).abs() <= 2);
assert!((font.space() - 218_454).abs() <= 2);
assert!(font.stretch() > 0);
assert!(font.shrink() > 0);
assert!(font.height('A') > 0);
assert!(font.depth('g') > 0);
}
#[test]
fn times_bold_and_italic_tfms_differ_from_roman() {
let roman = Cmr10Metrics::TimesRoman;
let differs = |face: Cmr10Metrics| {
['A', 'm', 'W', 'f']
.iter()
.any(|character| face.width(*character) != roman.width(*character))
};
assert!(differs(Cmr10Metrics::TimesBold));
assert!(differs(Cmr10Metrics::TimesItalic));
assert!(differs(Cmr10Metrics::TimesBoldItalic));
}
#[test]
fn times_roman_tfm_differs_from_cmr() {
let roman = Cmr10Metrics::Roman;
let times = Cmr10Metrics::TimesRoman;
assert_ne!(times.width('A'), roman.width('A'));
assert_ne!(times.width('m'), roman.width('m'));
assert!(times.height('A') > 0);
assert!(times.depth('g') > 0);
}
#[test]
fn bold_and_italic_tfms_differ_from_roman() {
let roman = Cmr10Metrics::Roman;
let bold = Cmr10Metrics::Bold;
let italic = Cmr10Metrics::Italic;
assert_ne!(bold.width('m'), roman.width('m'));
assert_ne!(italic.width('m'), roman.width('m'));
assert!(bold.space() > 0);
assert!(italic.height('A') > 0);
}
#[test]
fn math_face_uses_cmmi_for_letters() {
let roman = Cmr10Metrics::Roman;
let math = Cmr10Metrics::Math;
assert_ne!(math.width('f'), roman.width('f'));
assert_eq!(math.width('2'), roman.width('2'));
assert!(math.is_math());
}
#[test]
fn cmex_provides_big_operator_metrics() {
let (sum_width, _, sum_depth) = cmex_operator("sum").expect("cmex has a sum glyph");
let (int_width, _, _) = cmex_operator("int").expect("cmex has an integral glyph");
assert!(sum_width > 600_000, "sum width {sum_width}");
assert!(sum_depth > 500_000, "sum depth {sum_depth}");
assert!(int_width < sum_width);
assert!(cmex_operator("not-an-operator").is_none());
}
}
/// Map a Unicode math symbol to its slot in the bundled cmsy10 font.
pub fn math_symbol_slot(character: char) -> Option<u8> {
let slot = match character {
'\u{00B7}' => 2, // \cdot
'\u{00D7}' => 3, // \times
'\u{00F7}' => 5, // \div
'\u{00B1}' => 7, // \pm
'\u{2213}' => 8, // \mp
'\u{2295}' => 9, // \oplus
'\u{2296}' => 10, // \ominus
'\u{2297}' => 11, // \otimes
'\u{2298}' => 12, // \oslash
'\u{2299}' => 13, // \odot
'\u{224D}' => 17, // \asymp
'\u{2261}' => 18, // \equiv
'\u{2286}' => 19, // \subseteq
'\u{2287}' => 20, // \supseteq
'\u{2264}' => 21, // \leq
'\u{2265}' => 22, // \geq
'\u{2AAF}' => 23, // \preceq
'\u{2AB0}' => 24, // \succeq
'\u{223C}' => 25, // \sim
'\u{2248}' => 26, // \approx
'\u{2282}' => 27, // \subset
'\u{2283}' => 28, // \supset
'\u{226A}' => 29, // \ll
'\u{226B}' => 30, // \gg
'\u{227A}' => 31, // \prec
'\u{227B}' => 32, // \succ
'\u{2190}' => 33, // \leftarrow
'\u{2192}' => 34, // \rightarrow
'\u{2191}' => 35, // \uparrow
'\u{2193}' => 36, // \downarrow
'\u{2194}' => 37, // \leftrightarrow
'\u{2197}' => 38, // \nearrow
'\u{2198}' => 39, // \searrow
'\u{2243}' => 40, // \simeq
'\u{21D0}' => 41, // \Leftarrow
'\u{21D2}' => 42, // \Rightarrow
'\u{21D1}' => 43, // \Uparrow
'\u{21D3}' => 44, // \Downarrow
'\u{21D4}' => 45, // \Leftrightarrow
'\u{2196}' => 46, // \nwarrow
'\u{2199}' => 47, // \swarrow
'\u{221D}' => 48, // \propto
'\u{2032}' => 49, // \prime
'\u{221E}' => 50, // \infty
'\u{2208}' => 51, // \in
'\u{220B}' => 52, // \ni
'\u{25B3}' => 53, // \triangle
'\u{25BD}' => 54, // \triangledown
'\u{21A6}' => 56, // \mapsto
'\u{2200}' => 57, // \forall
'\u{2203}' => 58, // \exists
'\u{00AC}' => 59, // \neg
'\u{2205}' => 60, // \emptyset
'\u{211C}' => 61, // \Re
'\u{2111}' => 62, // \Im
'\u{22A4}' => 63, // \top
'\u{22A5}' => 64, // \bot
'\u{2135}' => 65, // \aleph
'\u{222A}' => 92, // \cup
'\u{2229}' => 93, // \cap
'\u{228E}' => 94, // \uplus
'\u{2227}' => 95, // \wedge
'\u{2228}' => 96, // \vee
'\u{22A2}' => 97, // \vdash
'\u{22A3}' => 98, // \dashv
'\u{230A}' => 99, // \lfloor
'\u{230B}' => 100, // \rfloor
'\u{2308}' => 101, // \lceil
'\u{2309}' => 102, // \rceil
'\u{007C}' => 107, // \vert
'\u{2016}' => 108, // \Vert
'\u{2195}' => 109, // \updownarrow
'\u{21D5}' => 110, // \Updownarrow
'\u{2240}' => 112, // \wr
'\u{2210}' => 114, // \coprod
'\u{2207}' => 115, // \nabla
'\u{222C}' | '\u{222D}' => 117,
'\u{2294}' => 117, // \sqcup
'\u{2293}' => 118, // \sqcap
'\u{00A7}' => 121, // \S
'\u{2020}' => 122, // \dagger
'\u{2021}' => 123, // \ddagger
'\u{00B6}' => 124, // \P
'\u{2663}' => 125, // \clubsuit
'\u{2662}' => 126, // \diamondsuit
'\u{2661}' => 127, // \heartsuit
'\u{2660}' => 128, // \spadesuit
_ => return None,
};
Some(slot)
}
#[cfg(test)]
mod cmsy_tests {
use super::*;
#[test]
fn cmsy_provides_math_symbol_metrics() {
let font = Cmr10Metrics::Math;
let times = font.width('\u{00D7}');
let slot = math_symbol_metrics().width(char::from(3u8));
assert_eq!(times, slot);
assert!(times > 0);
let less_equal = font.width('\u{2264}');
assert!(less_equal > 0);
assert_ne!(times, less_equal);
assert_eq!(Cmr10Metrics::Roman.width('\u{00D7}'), 327_680);
}
}
/// Metrics for a CMEX delimiter size variant: size 1 = `\big`, 2 = `\Big`,
/// 3 = `\bigg`, 4 = `\Bigg`.
pub fn cmex_delimiter(delimiter: char, size: u8) -> Option<(i64, i64, i64)> {
let slot = match (delimiter, size) {
('(', 1) => 1,
(')', 1) => 2,
('[', 1) => 3,
(']', 1) => 4,
('\u{230A}', 1) => 5,
('\u{230B}', 1) => 6,
('\u{2308}', 1) => 7,
('\u{2309}', 1) => 8,
('{', 1) => 9,
('}', 1) => 10,
('\u{27E8}', 1) => 11,
('\u{27E9}', 1) => 12,
('(', 2) => 17,
(')', 2) => 18,
('[', 2) => 105,
(']', 2) => 106,
('\u{230A}', 2) => 107,
('\u{230B}', 2) => 108,
('\u{2308}', 2) => 109,
('\u{2309}', 2) => 110,
('{', 2) => 111,
('}', 2) => 112,
('\u{27E8}', 2) => 69,
('\u{27E9}', 2) => 70,
('(', 3) => 19,
(')', 3) => 20,
('[', 3) => 21,
(']', 3) => 22,
('\u{230A}', 3) => 23,
('\u{230B}', 3) => 24,
('\u{2308}', 3) => 25,
('\u{2309}', 3) => 26,
('{', 3) => 27,
('}', 3) => 28,
('\u{27E8}', 3) => 29,
('\u{27E9}', 3) => 30,
('(', 4) => 33,
(')', 4) => 34,
('[', 4) => 35,
(']', 4) => 36,
('\u{230A}', 4) => 37,
('\u{230B}', 4) => 38,
('\u{2308}', 4) => 39,
('\u{2309}', 4) => 40,
('{', 4) => 41,
('}', 4) => 42,
('\u{27E8}', 4) => 43,
('\u{27E9}', 4) => 44,
_ => return None,
};
let metrics = math_extension_metrics();
let code = char::from(slot);
// CMEX delimiters sit almost entirely below the baseline; TeX centres them
// on the math axis (a quarter em at 10pt) before reporting height/depth.
let extent = metrics.height(code) + metrics.depth(code);
let axis = 655_360 / 4;
Some((
metrics.width(code),
extent / 2 + axis,
(extent / 2 - axis).max(0),
))
}
#[cfg(test)]
mod cmex_delimiter_tests {
use super::*;
#[test]
fn cmex_delimiters_have_distinct_size_variants() {
let big = cmex_delimiter('(', 1).expect("cmex has a big paren");
let big_big = cmex_delimiter('(', 2).expect("cmex has a Big paren");
let bigg = cmex_delimiter('(', 3).expect("cmex has a bigg paren");
let bigg_bigg = cmex_delimiter('(', 4).expect("cmex has a Bigg paren");
assert!(big.0 > 0 && big.1 > 0);
assert!(big_big.1 > big.1);
assert!(bigg.1 > big_big.1);
assert!(bigg_bigg.1 > bigg.1);
let extent = |m: (i64, i64, i64)| m.1 + m.2;
assert!(extent(big_big) > extent(big));
assert!(extent(bigg) > extent(big_big));
assert!(extent(bigg_bigg) > extent(bigg));
assert!(cmex_delimiter('.', 1).is_none());
assert!(cmex_delimiter('x', 1).is_none());
}
#[test]
fn sans_bold_and_italic_use_their_own_metrics() {
let regular = Cmr10Metrics::Sans.width('A');
let bold = Cmr10Metrics::SansBold.width('A');
let italic = Cmr10Metrics::SansItalic.width('A');
assert_eq!(bold, metrics_for(Cmr10Metrics::SansBold).width('A'));
assert_eq!(italic, metrics_for(Cmr10Metrics::SansItalic).width('A'));
assert_ne!(regular, bold);
assert_ne!(Cmr10Metrics::Sans.space(), Cmr10Metrics::SansBold.space());
assert!(italic > 0);
assert_eq!(Cmr10Metrics::for_pdf_slot(11), Cmr10Metrics::SansBold);
assert_eq!(Cmr10Metrics::for_pdf_slot(12), Cmr10Metrics::SansItalic);
assert_eq!(Cmr10Metrics::for_pdf_slot(13), Cmr10Metrics::SmallCaps);
let small_caps = Cmr10Metrics::SmallCaps.width('a');
assert_eq!(small_caps, metrics_for(Cmr10Metrics::SmallCaps).width('a'));
assert_ne!(small_caps, Cmr10Metrics::Roman.width('a'));
assert_eq!(Cmr10Metrics::for_pdf_slot(14), Cmr10Metrics::Slanted);
assert_eq!(Cmr10Metrics::for_pdf_slot(15), Cmr10Metrics::BoldSlanted);
assert_eq!(Cmr10Metrics::for_pdf_slot(16), Cmr10Metrics::MonoItalic);
let slanted = Cmr10Metrics::Slanted.width('a');
assert_eq!(slanted, metrics_for(Cmr10Metrics::Slanted).width('a'));
assert_ne!(slanted, Cmr10Metrics::Italic.width('a'));
assert_eq!(
Cmr10Metrics::BoldSlanted.width('a'),
metrics_for(Cmr10Metrics::BoldSlanted).width('a')
);
assert_eq!(
Cmr10Metrics::MonoItalic.width('a'),
metrics_for(Cmr10Metrics::MonoItalic).width('a')
);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,66 @@
//! Visit the font instances retained by packed glyphs in a format.
use super::*;
use crate::{math_engine_tex::MathItem, native_font::NativeFont};
use std::sync::Arc;
impl NativeBox {
pub(in crate::execution) fn visit_format_fonts_mut(
&mut self,
visit: &mut impl FnMut(&mut Arc<NativeFont>),
) {
match &mut self.content {
BoxContent::Horizontal(nodes) => rebind_horizontal(Arc::make_mut(nodes).as_mut_slice(), visit),
BoxContent::Vertical(nodes) => rebind_vertical(Arc::make_mut(nodes).as_mut_slice(), visit),
}
}
}
fn rebind_horizontal(nodes: &mut [TextNode], visit: &mut impl FnMut(&mut Arc<NativeFont>)) {
for node in nodes {
match node {
TextNode::Glyph { glyph, .. } | TextNode::Box(glyph) | TextNode::MathChar(glyph) => {
if let Some(b) = &mut glyph.native_box {
b.visit_format_fonts_mut(visit);
}
if let Some(geometry) = &mut glyph.math_geometry {
for item in &mut geometry.items {
if let MathItem::NativeGlyph { font, .. } = &mut item.item {
visit(font);
}
}
}
}
TextNode::Discretionary {
pre_break,
post_break,
..
} => {
rebind_horizontal(pre_break, visit);
rebind_horizontal(post_break, visit);
}
TextNode::Adjustment(value) => rebind_vertical(&mut value.nodes, visit),
TextNode::Insertion(value) => rebind_vertical(&mut value.nodes, visit),
TextNode::Leaders(leader) => rebind_leader(leader, visit),
_ => {}
}
}
}
fn rebind_vertical(nodes: &mut [NativeVerticalNode], visit: &mut impl FnMut(&mut Arc<NativeFont>)) {
for node in nodes {
match node {
NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => {
b.visit_format_fonts_mut(visit);
}
NativeVerticalNode::Insertion(value) => rebind_vertical(&mut value.nodes, visit),
NativeVerticalNode::Leaders(leader) => rebind_leader(leader, visit),
_ => {}
}
}
}
fn rebind_leader(leader: &mut LeaderGlue, visit: &mut impl FnMut(&mut Arc<NativeFont>)) {
if let LeaderPattern::Box(b) = &mut leader.pattern {
b.visit_format_fonts_mut(visit);
}
}
@@ -0,0 +1,230 @@
//! Shape full native word sequences after horizontal glue has been set.
use super::super::paragraph::interword::invisible;
use super::*;
use crate::{opentype::OpenTypeRun, provenance::PaintSource};
use std::{ops::Range, sync::Arc};
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(in crate::execution) struct Run {
pub(super) nodes: Range<usize>,
pub(in crate::execution) word: Arc<OpenTypeRun>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) effects: Vec<usize>,
}
impl NativeBox {
pub(in crate::execution) fn prepare_interword_shipout(
&mut self,
limit: usize,
cancellation: Option<&Cancellation>,
) -> Result<usize, String> {
let mut remaining = limit;
prepare(self, &mut remaining, cancellation)?;
Ok(limit - remaining)
}
}
fn prepare(
packed: &mut NativeBox,
remaining: &mut usize,
cancellation: Option<&Cancellation>,
) -> Result<(), String> {
if cancellation.is_some_and(Cancellation::is_cancelled) {
return Err("native compilation cancelled".into());
}
if packed.kind.is_unset() {
return Ok(());
}
match &mut packed.content {
BoxContent::Horizontal(nodes) => {
packed.interword_runs = shape_row(nodes, packed.setting, remaining, cancellation)?;
for node in Arc::make_mut(nodes) {
let child = match node {
TextNode::Box(item)
| TextNode::MathChar(item)
| TextNode::Glyph { glyph: item, .. } => item.native_box.as_deref_mut(),
TextNode::Leaders(LeaderGlue {
pattern: LeaderPattern::Box(item),
..
}) => Some(item.as_mut()),
_ => None,
};
if let Some(child) = child {
prepare(child, remaining, cancellation)?;
}
}
}
BoxContent::Vertical(nodes) => {
for node in Arc::make_mut(nodes) {
let child = match node {
NativeVerticalNode::Box(item)
| NativeVerticalNode::Line(item)
| NativeVerticalNode::Leaders(LeaderGlue {
pattern: LeaderPattern::Box(item),
..
}) => item,
_ => continue,
};
prepare(child, remaining, cancellation)?;
}
}
}
Ok(())
}
fn shape_row(
nodes: &[TextNode],
setting: GlueSetting,
remaining: &mut usize,
cancellation: Option<&Cancellation>,
) -> Result<Vec<Run>, String> {
let next = |start: usize| {
let offset = nodes[start..].iter().position(|node| !invisible(node));
offset.map_or(nodes.len(), |offset| start + offset)
};
let mut runs = Vec::new();
let mut moved_suffix_effects = false;
let mut index = 0;
while let Some(node) = nodes.get(index) {
let start = index;
index += 1;
let TextNode::OpenType(first) = node else {
continue;
};
if first.font.letter_space() != 0 {
continue;
}
let mut text = String::new();
let mut sources = Vec::new();
let mut units = 0;
loop {
let mut word_index = next(index);
let space = match nodes.get(word_index) {
Some(TextNode::FontSpace(_, font, origin)) => {
Some((Some(*origin), *font == first.font.id))
}
Some(TextNode::Glue(_)) => Some((None, false)),
_ => None,
};
if let Some((_, canonical)) = space {
let adjustment = matches!(
nodes.get(word_index + 1),
Some(TextNode::SpaceAdjustment(_))
);
if !canonical && !adjustment {
break;
}
word_index = next(word_index + 1 + usize::from(adjustment));
}
let Some(TextNode::OpenType(word)) = nodes.get(word_index) else {
break;
};
if word.font.id != first.font.id {
break;
}
if index == start + 1 {
text.push_str(&first.text);
sources.extend(first.sources.iter().cloned());
units = first.text.encode_utf16().count();
}
if let Some((origin, _)) = space {
if let Some(origin) = origin {
sources.push((text.len(), PaintSource::token(origin)));
}
text.push(' ');
units += 1;
}
units += word.text.encode_utf16().count();
if units > usize::from(u16::MAX) {
return Err("native justified OpenType word capacity exceeded".into());
}
let offset = text.len();
text.push_str(&word.text);
sources.extend(
word.sources
.iter()
.map(|(at, source)| (offset + at, source.clone())),
);
index = word_index + 1;
}
if index == start + 1 {
continue;
}
if cancellation.is_some_and(Cancellation::is_cancelled) {
return Err("native compilation cancelled".into());
}
let mut word = first.font.shape_mapped(text, sources, false)?;
*remaining = remaining
.checked_sub(word.glyphs.len())
.ok_or("native justified OpenType shaping step limit exceeded")?;
let target = nodes[start..index]
.iter()
.map(|node| shipout_width(node, setting))
.sum();
word.actual_text = first.actual_text;
justify(&mut word, target)?;
let mut effects = Vec::new();
if !moved_suffix_effects
&& let Some(offset) = nodes[start + 1..index].iter().position(invisible)
{
// XDV relinks the first invisible node in the old run. The scan
// then follows its new link into the remaining horizontal list.
effects.push(start + 1 + offset);
effects.extend(
nodes[index..]
.iter()
.enumerate()
.filter_map(|(offset, node)| invisible(node).then_some(index + offset)),
);
moved_suffix_effects = true;
}
runs.push(Run {
nodes: start..index,
word: Arc::new(word),
effects,
});
}
Ok(runs)
}
fn shipout_width(node: &TextNode, setting: GlueSetting) -> i64 {
match node {
TextNode::Glue(glue) | TextNode::FontSpace(glue, ..) => {
// XeTeX rounds each consumed space independently before joining.
let (mut cumulative, mut previous) = (0, 0);
i64::from(glue.width) + setting.adjustment(*glue, &mut cumulative, &mut previous)
}
TextNode::OpenType(word) => word.width,
TextNode::SpaceAdjustment(width) => i64::from(*width),
_ => 0,
}
}
fn justify(word: &mut OpenTypeRun, target: i64) -> Result<(), String> {
let difference = target - word.width;
word.width = target;
if difference == 0 || word.glyphs.len() < 2 {
return Ok(());
}
let space = word
.font
.face()?
.glyph_index(' ')
.map_or(0, |glyph| glyph.0);
let spaces = word.glyphs.iter().filter(|glyph| glyph.id == space).count();
let total = if spaces == 0 {
word.glyphs.len() - 1
} else {
spaces
};
let mut consumed = 0;
for glyph in &mut word.glyphs {
glyph.x =
(glyph.x as f64 + difference as f64 * consumed as f64 / total as f64).round() as i64;
if spaces == 0 || glyph.id == space {
consumed += 1;
}
}
Ok(())
}
@@ -0,0 +1,74 @@
//! Owned leader glue. The pattern is kept once even when it paints many times.
use super::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum LeaderMode {
Aligned,
Centered,
Expanded,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum LeaderPattern {
Box(Box<NativeBox>),
Rule(NativeRule),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct LeaderGlue {
pub glue: Glue,
pub mode: LeaderMode,
pub pattern: LeaderPattern,
}
impl LeaderGlue {
pub(super) fn pattern_dimensions(&self) -> (i64, i64, i64) {
match &self.pattern {
LeaderPattern::Box(b) => (b.width, b.height - b.shift, b.depth + b.shift),
LeaderPattern::Rule(r) => r.dimensions(),
}
}
pub(super) fn positions(
&self,
origin: i64,
start: i64,
available: i64,
tile: i64,
) -> impl Iterator<Item = i64> {
let (first, stride, count) = if tile <= 0 || available <= 0 {
(start, 0, 0)
} else {
// TeX includes 10 sp in its fit check to absorb glue rounding.
// The caller still advances by the original adjusted glue length.
let length = available + 10;
let copies = length / tile;
let remaining = length % tile;
let (offset, gap) = match self.mode {
LeaderMode::Aligned => ((origin - start).rem_euclid(tile), 0),
LeaderMode::Centered => (remaining / 2, 0),
LeaderMode::Expanded => {
let gap = remaining / (copies + 1);
((remaining - (copies - 1) * gap) / 2, gap)
}
};
let stride = tile + gap;
let count = if length - offset >= tile {
1 + (length - offset - tile) / stride
} else {
0
};
(start + offset, stride, count)
};
(0..count).map(move |copy| first + copy * stride)
}
}
impl LeaderPattern {
pub(in crate::execution) fn node_count(&self) -> usize {
match self {
Self::Box(b) => b.node_count(),
Self::Rule(_) => 1,
}
}
}
@@ -0,0 +1,94 @@
//! Reassemble XeTeX native word fragments in the physical horizontal list.
use super::TextNode;
use std::sync::Arc;
pub(super) fn rejoin(
nodes: &mut Vec<TextNode>,
glyph_metrics: bool,
mut shaping_budget: Option<(&mut usize, usize)>,
) -> Result<(), String> {
let mut index = 0;
let mut replacement_left = 0;
let mut edits = Vec::new();
while let Some(node) = nodes.get(index) {
let begin = index;
index += 1;
if let TextNode::Discretionary {
replacement_count, ..
} = node
{
replacement_left = *replacement_count;
continue;
}
if replacement_left > 0 {
replacement_left -= 1;
continue;
}
let TextNode::OpenType(first) = node else {
continue;
};
// Each retained discretionary may bridge one pair of fragments.
// Starting inside a live replacement would invalidate its node count.
loop {
let next = index
+ usize::from(matches!(
nodes.get(index),
Some(TextNode::Discretionary { .. })
));
if !matches!(nodes.get(next), Some(TextNode::OpenType(run)) if run.font.id == first.font.id)
{
break;
}
index = next + 1;
}
if index == begin + 1 {
continue;
}
let mut text = String::new();
let mut sources = Vec::new();
let mut units = 0;
for node in &nodes[begin..index] {
if let TextNode::OpenType(run) = node {
units += run.text.encode_utf16().count();
if units > usize::from(u16::MAX) {
return Err("native OpenType word capacity exceeded".into());
}
let offset = text.len();
sources.extend(
run.sources
.iter()
.map(|(at, source)| (offset + at, source.clone())),
);
text.push_str(&run.text);
}
}
let mut word = first.font.shape_mapped(text, sources, glyph_metrics)?;
word.actual_text = first.actual_text;
if let Some((steps, limit)) = &mut shaping_budget {
**steps = steps
.checked_add(word.glyphs.len())
.filter(|work| work <= limit)
.ok_or("native OpenType packing step limit exceeded")?;
}
edits.push((begin, index, Arc::new(word)));
}
if !edits.is_empty() {
let mut edits = edits.into_iter().peekable();
let mut index = 0;
let mut discard_until = 0;
nodes.retain_mut(|node| {
let at = index;
index += 1;
if at < discard_until {
return false;
}
if let Some((_, end, word)) = edits.next_if(|(begin, _, _)| *begin == at) {
*node = TextNode::OpenType(word);
discard_until = end;
}
true
});
}
Ok(())
}
@@ -0,0 +1,207 @@
//! Owned list-tail cursors, independent of the list's enclosing root vector.
use super::*;
pub(in crate::execution) enum TailNodeRef<'a> {
Vertical(&'a NativeVerticalNode),
Text(&'a TextNode),
}
enum Removed {
Vertical(NativeVerticalNode),
Text(TextNode),
}
fn vertical_box(n: &NativeVerticalNode) -> &NativeBox {
match n {
NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => b,
_ => unreachable!("owned list cursor must enter a real box"),
}
}
fn vertical_box_mut(n: &mut NativeVerticalNode) -> &mut NativeBox {
match n {
NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => b,
_ => unreachable!("owned list cursor must enter a real box"),
}
}
fn text_box(n: &TextNode) -> &NativeBox {
match n {
TextNode::Box(b) => b.native_box.as_deref().expect("owned list cursor box"),
_ => unreachable!("owned list cursor must enter a real box"),
}
}
fn text_box_mut(n: &mut TextNode) -> &mut NativeBox {
match n {
TextNode::Box(b) => b.native_box.as_deref_mut().expect("owned list cursor box"),
_ => unreachable!("owned list cursor must enter a real box"),
}
}
fn descend<'a>(b: &'a NativeBox, path: &[usize]) -> &'a NativeBox {
match path.split_first() {
None => b,
Some((&i, rest)) => descend(
match &b.content {
BoxContent::Vertical(v) => vertical_box(&v[i]),
BoxContent::Horizontal(v) => text_box(&v[i]),
},
rest,
),
}
}
fn descend_mut<'a>(b: &'a mut NativeBox, path: &[usize]) -> &'a mut NativeBox {
match path.split_first() {
None => b,
Some((&i, rest)) => descend_mut(
match &mut b.content {
BoxContent::Vertical(v) => vertical_box_mut(&mut Arc::make_mut(v)[i]),
BoxContent::Horizontal(v) => text_box_mut(&mut Arc::make_mut(v)[i]),
},
rest,
),
}
}
fn refresh(b: &mut NativeBox, path: &[usize]) {
if let Some((&i, rest)) = path.split_first() {
let child = match &mut b.content {
BoxContent::Vertical(v) => vertical_box_mut(&mut Arc::make_mut(v)[i]),
BoxContent::Horizontal(v) => text_box_mut(&mut Arc::make_mut(v)[i]),
};
refresh(child, rest);
}
if let BoxContent::Horizontal(v) = &b.content {
b.diagnostic = crate::execution::diagnostics::text_nodes(v).into();
}
}
fn horizontal(n: NativeVerticalNode) -> TextNode {
match n {
NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => TextNode::Box(HorizontalBox {
width: b.width,
height: b.height,
depth: b.depth,
native_box: Some(b),
..HorizontalBox::default()
}),
NativeVerticalNode::Glue(g) => TextNode::Glue(g),
NativeVerticalNode::NamedGlue(g, p) => TextNode::NamedGlue(g, p),
NativeVerticalNode::Leaders(l) => TextNode::Leaders(l),
NativeVerticalNode::Kern(width) => TextNode::Kern {
width,
explicit: true,
},
NativeVerticalNode::ImplicitKern(width) => TextNode::Kern {
width,
explicit: false,
},
NativeVerticalNode::Penalty(n) => TextNode::Penalty(n),
NativeVerticalNode::Rule(r) => TextNode::Rule(r),
NativeVerticalNode::Mark(m) => TextNode::Mark(m),
NativeVerticalNode::Insertion(n) => TextNode::Insertion(n),
NativeVerticalNode::Output(o) => TextNode::Output(o),
}
}
impl VerticalBuilder {
fn tail_box(&self) -> Option<&NativeBox> {
self.tail_path
.split_first()
.map(|(&i, rest)| descend(vertical_box(&self.nodes[i]), rest))
}
fn tail_box_mut(&mut self) -> Option<&mut NativeBox> {
self.tail_path
.split_first()
.map(|(&i, rest)| descend_mut(vertical_box_mut(&mut self.nodes[i]), rest))
}
fn refresh_tail(&mut self) {
if let Some((&i, rest)) = self.tail_path.split_first() {
refresh(vertical_box_mut(&mut self.nodes[i]), rest);
}
}
fn tail_len(&self) -> usize {
match self.tail_box().map(|b| &b.content) {
None => self.nodes.len(),
Some(BoxContent::Vertical(v)) => v.len(),
Some(BoxContent::Horizontal(v)) => v.len(),
}
}
pub(in crate::execution) fn tail_depth(&self) -> usize {
self.tail_path.len()
}
pub(in crate::execution) fn nest_tail_in(&mut self, index: usize) {
if self.tail_path.is_empty() && index + 1 == self.nodes.len() {
self.tail_path.push(index);
}
}
pub(in crate::execution) fn push(&mut self, node: NativeVerticalNode) {
match self.tail_box_mut().map(|b| &mut b.content) {
None => self.nodes.push(node),
Some(BoxContent::Vertical(v)) => Arc::make_mut(v).push(node),
Some(BoxContent::Horizontal(v)) => Arc::make_mut(v).push(horizontal(node)),
}
self.refresh_tail();
}
pub(in crate::execution) fn extend(
&mut self,
nodes: impl IntoIterator<Item = NativeVerticalNode>,
) {
for node in nodes {
self.push(node);
}
}
pub(in crate::execution) fn append(&mut self, nodes: &mut Vec<NativeVerticalNode>) {
self.extend(std::mem::take(nodes));
}
pub(in crate::execution) fn append_builder(&mut self, other: Self) {
let base = self.tail_len();
let mut path = other.tail_path;
self.extend(other.nodes);
if let Some(first) = path.first_mut() {
*first += base;
self.tail_path.extend(path);
}
}
pub(in crate::execution) fn take_nodes(&mut self) -> Vec<NativeVerticalNode> {
self.tail_path.clear();
std::mem::take(&mut self.nodes)
}
pub(in crate::execution) fn tail_ref(&self) -> Option<TailNodeRef<'_>> {
match self.tail_box().map(|b| &b.content) {
None => self.nodes.last().map(TailNodeRef::Vertical),
Some(BoxContent::Vertical(v)) => v.last().map(TailNodeRef::Vertical),
Some(BoxContent::Horizontal(v)) => v.last().map(TailNodeRef::Text),
}
}
fn pop(&mut self) -> Option<Removed> {
let node = match self.tail_box_mut().map(|b| &mut b.content) {
None => self.nodes.pop().map(Removed::Vertical),
Some(BoxContent::Vertical(v)) => Arc::make_mut(v).pop().map(Removed::Vertical),
Some(BoxContent::Horizontal(v)) => Arc::make_mut(v).pop().map(Removed::Text),
};
self.refresh_tail();
node
}
pub(in crate::execution) fn remove_tail(&mut self) -> Result<(), String> {
if !self.tail_path.is_empty() {
return Err(
"cannot unlink a native list tail not reachable from its active head".into(),
);
}
self.pop();
Ok(())
}
pub(in crate::execution) fn take_last_box(&mut self) -> Result<Option<NativeBox>, String> {
let is_box = matches!(
self.tail_ref(),
Some(TailNodeRef::Vertical(NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b))) if !b.kind.is_unset()
) || matches!(self.tail_ref(), Some(TailNodeRef::Text(TextNode::Box(b))) if b.native_box.as_ref().is_some_and(|b| !b.kind.is_unset())
);
if !is_box {
return Ok(None);
}
if !self.tail_path.is_empty() {
return Err(
"cannot unlink a native list tail not reachable from its active head".into(),
);
}
Ok(match self.pop().unwrap() {
Removed::Vertical(NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b)) => Some(*b),
Removed::Text(TextNode::Box(b)) => b.native_box.map(|b| *b),
_ => unreachable!("checked actual tail box"),
})
}
}
@@ -0,0 +1,110 @@
//! Web2C character translation and printability for physical TeX byte I/O.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ByteTranslation {
input: [[u8; 32]; 8],
output: [[u8; 32]; 8],
printable: [u64; 4],
}
impl Default for ByteTranslation {
fn default() -> Self {
let identity =
std::array::from_fn(|row| std::array::from_fn(|column| (row * 32 + column) as u8));
Self {
input: identity,
output: identity,
printable: [u64::MAX << 32, u64::MAX >> 1, 0, 0],
}
}
}
impl ByteTranslation {
pub fn from_tcx(data: &[u8]) -> Result<Self, String> {
let mut table = Self::default();
for (line, bytes) in data.split(|&b| b == b'\n').enumerate() {
let record = bytes.split(|&b| b == b'%').next().unwrap_or_default();
let record = std::str::from_utf8(record)
.map_err(|_| format!("invalid TCX entry on line {}", line + 1))?;
let mut fields = record.split_ascii_whitespace();
let Some(field) = fields.next() else {
continue;
};
let parse = |field| {
number(field).ok_or_else(|| format!("invalid TCX entry on line {}", line + 1))
};
let external = parse(field)?;
let internal = if let Some(field) = fields.next() {
let internal = parse(field)?;
table.input[usize::from(external) / 32][usize::from(external) % 32] = internal;
table.output[usize::from(internal) / 32][usize::from(internal) % 32] = external;
internal
} else {
external
};
let printable = match fields.next() {
Some(field) => match parse(field)? {
0 => false,
1 => true,
_ => return Err(format!("invalid TCX printable flag on line {}", line + 1)),
},
None => true,
};
let mask = 1_u64 << (internal % 64);
let entry = &mut table.printable[usize::from(internal) / 64];
if printable || (32..=126).contains(&internal) {
*entry |= mask;
} else {
*entry &= !mask;
}
}
Ok(table)
}
pub(super) fn input(&self, value: u8) -> u8 {
self.input[usize::from(value) / 32][usize::from(value) % 32]
}
pub(super) fn output(&self, value: u8) -> u8 {
self.output[usize::from(value) / 32][usize::from(value) % 32]
}
pub(super) fn printable(&self, value: u8) -> bool {
self.printable[usize::from(value) / 64] & (1_u64 << (value % 64)) != 0
}
}
fn number(field: &str) -> Option<u8> {
let field = field.strip_prefix('+').unwrap_or(field);
if let Some(hex) = field
.strip_prefix("0x")
.or_else(|| field.strip_prefix("0X"))
{
u8::from_str_radix(hex, 16).ok()
} else if field.len() > 1 && field.starts_with('0') {
u8::from_str_radix(field, 8).ok()
} else {
field.parse().ok()
}
}
pub(super) fn diagnostic_text(bytes: &[u8]) -> String {
let mut text = String::new();
let mut remaining = bytes;
loop {
match std::str::from_utf8(remaining) {
Ok(valid) => {
text.push_str(valid);
return text;
}
Err(error) => {
let start = error.valid_up_to();
let end = start + error.error_len().unwrap_or(remaining.len() - start);
text.push_str(std::str::from_utf8(&remaining[..start]).unwrap());
for &byte in &remaining[start..end] {
text.push_str(&super::context::encoded_character(char::from(byte)));
}
remaining = &remaining[end..];
}
}
}
}
@@ -0,0 +1,18 @@
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
/// A shared stop signal for one native compilation.
#[derive(Clone, Debug, Default)]
pub struct Cancellation(Arc<AtomicBool>);
impl Cancellation {
pub fn cancel(&self) {
self.0.store(true, Ordering::Release);
}
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::Acquire)
}
}
Loaded 100 of 731 files, more files were not shown because too many files have changed in this diff. Show more