From bb1d9e05617abae48bae28c24ea0920d9958542f Mon Sep 17 00:00:00 2001 From: GloamXun Date: Mon, 19 Oct 2026 11:41:46 +0800 Subject: [PATCH] Initial texrra engine Rename the crate, binary, core crate, font families, env vars, and internal commands from texcraft/tex-engine to texrra. Serve the separately versioned texrra-web frontend from TEXRRA_WEB_DIR, ../web, or ./web instead of embedding index.html. Add starred section heading support and an arXiv template conformance fixture. --- .gitignore | 2 + Cargo.lock | 1201 +++ Cargo.toml | 34 + README.md | 442 + crates/texrra-core/Cargo.toml | 15 + crates/texrra-core/src/assignment_scope.rs | 85 + crates/texrra-core/src/command.rs | 116 + crates/texrra-core/src/document.rs | 279 + crates/texrra-core/src/document_parser.rs | 1717 ++++ crates/texrra-core/src/environment.rs | 63 + crates/texrra-core/src/expanded.rs | 617 ++ crates/texrra-core/src/expansion.rs | 470 + crates/texrra-core/src/glue.rs | 77 + crates/texrra-core/src/input.rs | 281 + crates/texrra-core/src/integer.rs | 215 + crates/texrra-core/src/layout_primitive.rs | 54 + crates/texrra-core/src/lib.rs | 483 ++ crates/texrra-core/src/macros.rs | 477 + crates/texrra-core/src/math_alphabet.rs | 609 ++ crates/texrra-core/src/math_code.rs | 276 + crates/texrra-core/src/math_constants.rs | 411 + crates/texrra-core/src/math_expr.rs | 1424 +++ crates/texrra-core/src/math_glyph.rs | 137 + crates/texrra-core/src/math_layout.rs | 1513 ++++ crates/texrra-core/src/math_list.rs | 403 + crates/texrra-core/src/math_lowering.rs | 1354 +++ crates/texrra-core/src/math_mode.rs | 344 + crates/texrra-core/src/math_parser.rs | 2072 +++++ crates/texrra-core/src/math_style.rs | 97 + crates/texrra-core/src/mouth.rs | 553 ++ crates/texrra-core/src/references.rs | 90 + crates/texrra-core/src/source.rs | 16 + crates/texrra-core/src/state.rs | 74 + docs/ROADMAP.md | 72 + docs/STATUS.md | 56 + docs/compiler-architecture.md | 1144 +++ docs/xetex-rust-port-map.md | 357 + examples/boxes.tex | 24 + examples/compat.tex | 35 + examples/hello.tex | 35 + examples/plot.png | Bin 0 -> 1717 bytes examples/references.bib | 20 + examples/texrra-extra.sty | 3 + fixtures/README.md | 8 + fixtures/arxiv-template/License.txt | 21 + fixtures/arxiv-template/README.md | 49 + fixtures/arxiv-template/arxiv.sty | 262 + fixtures/arxiv-template/orcid.pdf | Bin 0 -> 12397 bytes fixtures/arxiv-template/references.bib | 27 + fixtures/arxiv-template/template.tex | 214 + src/main.rs | 615 ++ src/projects.rs | 764 ++ src/rust_typeset.rs | 1356 +++ src/rust_typeset/box_font.rs | 191 + src/rust_typeset/document.rs | 4 + src/rust_typeset/engine/arithmetic.rs | 362 + src/rust_typeset/engine/assignment_scope.rs | 1 + src/rust_typeset/engine/command.rs | 1 + src/rust_typeset/engine/dimension.rs | 969 +++ src/rust_typeset/engine/environment.rs | 1 + src/rust_typeset/engine/expansion.rs | 1 + src/rust_typeset/engine/glue.rs | 1 + src/rust_typeset/engine/input.rs | 3 + src/rust_typeset/engine/layout_primitive.rs | 3 + src/rust_typeset/engine/macros.rs | 1 + src/rust_typeset/engine/math_code.rs | 1 + src/rust_typeset/engine/mod.rs | 18 + src/rust_typeset/engine/mouth.rs | 1 + src/rust_typeset/engine/prefix.rs | 176 + src/rust_typeset/engine/registers.rs | 63 + src/rust_typeset/engine/state.rs | 96 + .../engine/texlang_dimension_adapter.rs | 438 + src/rust_typeset/engine/token.rs | 2 + src/rust_typeset/engine/variable.rs | 62 + src/rust_typeset/frontend.rs | 831 ++ src/rust_typeset/math_font.rs | 1689 ++++ src/rust_typeset/math_layout.rs | 5054 +++++++++++ src/rust_typeset/page_builder.rs | 361 + src/rust_typeset/parser.rs | 3 + src/rust_typeset/pdf.rs | 2647 ++++++ src/rust_typeset/pdf/layout.rs | 2713 ++++++ src/rust_typeset/pdf/preview.rs | 358 + src/rust_typeset/texlang_adapter.rs | 7681 +++++++++++++++++ src/rust_typeset/text_layout.rs | 446 + vendor/hyphenate/Cargo.toml | 6 + vendor/hyphenate/src/lib.rs | 505 ++ vendor/hyphenate/src/plain_tex_exceptions.txt | 14 + vendor/hyphenate/src/plain_tex_patterns.txt | 4447 ++++++++++ vendor/texlang-stdlib/Cargo.toml | 54 + vendor/texlang-stdlib/README.md | 6 + vendor/texlang-stdlib/bin/errors.rs | 31 + vendor/texlang-stdlib/src/alias.rs | 138 + vendor/texlang-stdlib/src/alloc.rs | 268 + vendor/texlang-stdlib/src/chardef.rs | 62 + vendor/texlang-stdlib/src/codes.rs | 225 + vendor/texlang-stdlib/src/conditional.rs | 652 ++ vendor/texlang-stdlib/src/def.rs | 620 ++ vendor/texlang-stdlib/src/endlinechar.rs | 92 + vendor/texlang-stdlib/src/errormode.rs | 120 + vendor/texlang-stdlib/src/examples.rs | 111 + vendor/texlang-stdlib/src/expansion.rs | 418 + vendor/texlang-stdlib/src/input.rs | 581 ++ vendor/texlang-stdlib/src/job.rs | 183 + vendor/texlang-stdlib/src/lib.rs | 574 ++ vendor/texlang-stdlib/src/math.rs | 577 ++ vendor/texlang-stdlib/src/mathchardef.rs | 76 + vendor/texlang-stdlib/src/prefix.rs | 539 ++ vendor/texlang-stdlib/src/registers.rs | 475 + vendor/texlang-stdlib/src/repl.rs | 175 + vendor/texlang-stdlib/src/script.rs | 197 + vendor/texlang-stdlib/src/sleep.rs | 26 + vendor/texlang-stdlib/src/texcraft.rs | 41 + vendor/texlang-stdlib/src/the.rs | 173 + vendor/texlang-stdlib/src/time.rs | 97 + vendor/texlang-stdlib/src/tracingmacros.rs | 78 + vendor/texlang/Cargo.toml | 25 + vendor/texlang/LICENCE | 16 + vendor/texlang/README.md | 10 + vendor/texlang/src/command/map.rs | 590 ++ vendor/texlang/src/command/mod.rs | 428 + vendor/texlang/src/error/display.rs | 337 + vendor/texlang/src/error/mod.rs | 397 + vendor/texlang/src/lib.rs | 34 + vendor/texlang/src/parse/dimen.rs | 354 + vendor/texlang/src/parse/filelocation.rs | 199 + vendor/texlang/src/parse/glue.rs | 187 + vendor/texlang/src/parse/helpers.rs | 59 + vendor/texlang/src/parse/integer.rs | 588 ++ vendor/texlang/src/parse/keyword.rs | 34 + vendor/texlang/src/parse/mod.rs | 370 + vendor/texlang/src/parse/muglue.rs | 136 + vendor/texlang/src/parse/relation.rs | 70 + vendor/texlang/src/parse/testing.rs | 121 + vendor/texlang/src/parse/variable.rs | 47 + vendor/texlang/src/prelude.rs | 8 + vendor/texlang/src/texmacro.rs | 500 ++ vendor/texlang/src/token/lexer.rs | 1246 +++ vendor/texlang/src/token/mod.rs | 539 ++ vendor/texlang/src/token/trace.rs | 508 ++ vendor/texlang/src/types/catcode.rs | 1 + vendor/texlang/src/types/mathcode.rs | 11 + vendor/texlang/src/types/mod.rs | 73 + vendor/texlang/src/types/muglue.rs | 64 + vendor/texlang/src/variable.rs | 829 ++ vendor/texlang/src/vm/mod.rs | 1271 +++ vendor/texlang/src/vm/serde.rs | 127 + vendor/texlang/src/vm/streams.rs | 738 ++ 147 files changed, 66719 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 README.md create mode 100644 crates/texrra-core/Cargo.toml create mode 100644 crates/texrra-core/src/assignment_scope.rs create mode 100644 crates/texrra-core/src/command.rs create mode 100644 crates/texrra-core/src/document.rs create mode 100644 crates/texrra-core/src/document_parser.rs create mode 100644 crates/texrra-core/src/environment.rs create mode 100644 crates/texrra-core/src/expanded.rs create mode 100644 crates/texrra-core/src/expansion.rs create mode 100644 crates/texrra-core/src/glue.rs create mode 100644 crates/texrra-core/src/input.rs create mode 100644 crates/texrra-core/src/integer.rs create mode 100644 crates/texrra-core/src/layout_primitive.rs create mode 100644 crates/texrra-core/src/lib.rs create mode 100644 crates/texrra-core/src/macros.rs create mode 100644 crates/texrra-core/src/math_alphabet.rs create mode 100644 crates/texrra-core/src/math_code.rs create mode 100644 crates/texrra-core/src/math_constants.rs create mode 100644 crates/texrra-core/src/math_expr.rs create mode 100644 crates/texrra-core/src/math_glyph.rs create mode 100644 crates/texrra-core/src/math_layout.rs create mode 100644 crates/texrra-core/src/math_list.rs create mode 100644 crates/texrra-core/src/math_lowering.rs create mode 100644 crates/texrra-core/src/math_mode.rs create mode 100644 crates/texrra-core/src/math_parser.rs create mode 100644 crates/texrra-core/src/math_style.rs create mode 100644 crates/texrra-core/src/mouth.rs create mode 100644 crates/texrra-core/src/references.rs create mode 100644 crates/texrra-core/src/source.rs create mode 100644 crates/texrra-core/src/state.rs create mode 100644 docs/ROADMAP.md create mode 100644 docs/STATUS.md create mode 100644 docs/compiler-architecture.md create mode 100644 docs/xetex-rust-port-map.md create mode 100644 examples/boxes.tex create mode 100644 examples/compat.tex create mode 100644 examples/hello.tex create mode 100644 examples/plot.png create mode 100644 examples/references.bib create mode 100644 examples/texrra-extra.sty create mode 100644 fixtures/README.md create mode 100644 fixtures/arxiv-template/License.txt create mode 100644 fixtures/arxiv-template/README.md create mode 100644 fixtures/arxiv-template/arxiv.sty create mode 100644 fixtures/arxiv-template/orcid.pdf create mode 100644 fixtures/arxiv-template/references.bib create mode 100644 fixtures/arxiv-template/template.tex create mode 100644 src/main.rs create mode 100644 src/projects.rs create mode 100644 src/rust_typeset.rs create mode 100644 src/rust_typeset/box_font.rs create mode 100644 src/rust_typeset/document.rs create mode 100644 src/rust_typeset/engine/arithmetic.rs create mode 100644 src/rust_typeset/engine/assignment_scope.rs create mode 100644 src/rust_typeset/engine/command.rs create mode 100644 src/rust_typeset/engine/dimension.rs create mode 100644 src/rust_typeset/engine/environment.rs create mode 100644 src/rust_typeset/engine/expansion.rs create mode 100644 src/rust_typeset/engine/glue.rs create mode 100644 src/rust_typeset/engine/input.rs create mode 100644 src/rust_typeset/engine/layout_primitive.rs create mode 100644 src/rust_typeset/engine/macros.rs create mode 100644 src/rust_typeset/engine/math_code.rs create mode 100644 src/rust_typeset/engine/mod.rs create mode 100644 src/rust_typeset/engine/mouth.rs create mode 100644 src/rust_typeset/engine/prefix.rs create mode 100644 src/rust_typeset/engine/registers.rs create mode 100644 src/rust_typeset/engine/state.rs create mode 100644 src/rust_typeset/engine/texlang_dimension_adapter.rs create mode 100644 src/rust_typeset/engine/token.rs create mode 100644 src/rust_typeset/engine/variable.rs create mode 100644 src/rust_typeset/frontend.rs create mode 100644 src/rust_typeset/math_font.rs create mode 100644 src/rust_typeset/math_layout.rs create mode 100644 src/rust_typeset/page_builder.rs create mode 100644 src/rust_typeset/parser.rs create mode 100644 src/rust_typeset/pdf.rs create mode 100644 src/rust_typeset/pdf/layout.rs create mode 100644 src/rust_typeset/pdf/preview.rs create mode 100644 src/rust_typeset/texlang_adapter.rs create mode 100644 src/rust_typeset/text_layout.rs create mode 100644 vendor/hyphenate/Cargo.toml create mode 100644 vendor/hyphenate/src/lib.rs create mode 100644 vendor/hyphenate/src/plain_tex_exceptions.txt create mode 100644 vendor/hyphenate/src/plain_tex_patterns.txt create mode 100644 vendor/texlang-stdlib/Cargo.toml create mode 100644 vendor/texlang-stdlib/README.md create mode 100644 vendor/texlang-stdlib/bin/errors.rs create mode 100644 vendor/texlang-stdlib/src/alias.rs create mode 100644 vendor/texlang-stdlib/src/alloc.rs create mode 100644 vendor/texlang-stdlib/src/chardef.rs create mode 100644 vendor/texlang-stdlib/src/codes.rs create mode 100644 vendor/texlang-stdlib/src/conditional.rs create mode 100644 vendor/texlang-stdlib/src/def.rs create mode 100644 vendor/texlang-stdlib/src/endlinechar.rs create mode 100644 vendor/texlang-stdlib/src/errormode.rs create mode 100644 vendor/texlang-stdlib/src/examples.rs create mode 100644 vendor/texlang-stdlib/src/expansion.rs create mode 100644 vendor/texlang-stdlib/src/input.rs create mode 100644 vendor/texlang-stdlib/src/job.rs create mode 100644 vendor/texlang-stdlib/src/lib.rs create mode 100644 vendor/texlang-stdlib/src/math.rs create mode 100644 vendor/texlang-stdlib/src/mathchardef.rs create mode 100644 vendor/texlang-stdlib/src/prefix.rs create mode 100644 vendor/texlang-stdlib/src/registers.rs create mode 100644 vendor/texlang-stdlib/src/repl.rs create mode 100644 vendor/texlang-stdlib/src/script.rs create mode 100644 vendor/texlang-stdlib/src/sleep.rs create mode 100644 vendor/texlang-stdlib/src/texcraft.rs create mode 100644 vendor/texlang-stdlib/src/the.rs create mode 100644 vendor/texlang-stdlib/src/time.rs create mode 100644 vendor/texlang-stdlib/src/tracingmacros.rs create mode 100644 vendor/texlang/Cargo.toml create mode 100644 vendor/texlang/LICENCE create mode 100644 vendor/texlang/README.md create mode 100644 vendor/texlang/src/command/map.rs create mode 100644 vendor/texlang/src/command/mod.rs create mode 100644 vendor/texlang/src/error/display.rs create mode 100644 vendor/texlang/src/error/mod.rs create mode 100644 vendor/texlang/src/lib.rs create mode 100644 vendor/texlang/src/parse/dimen.rs create mode 100644 vendor/texlang/src/parse/filelocation.rs create mode 100644 vendor/texlang/src/parse/glue.rs create mode 100644 vendor/texlang/src/parse/helpers.rs create mode 100644 vendor/texlang/src/parse/integer.rs create mode 100644 vendor/texlang/src/parse/keyword.rs create mode 100644 vendor/texlang/src/parse/mod.rs create mode 100644 vendor/texlang/src/parse/muglue.rs create mode 100644 vendor/texlang/src/parse/relation.rs create mode 100644 vendor/texlang/src/parse/testing.rs create mode 100644 vendor/texlang/src/parse/variable.rs create mode 100644 vendor/texlang/src/prelude.rs create mode 100644 vendor/texlang/src/texmacro.rs create mode 100644 vendor/texlang/src/token/lexer.rs create mode 100644 vendor/texlang/src/token/mod.rs create mode 100644 vendor/texlang/src/token/trace.rs create mode 100644 vendor/texlang/src/types/catcode.rs create mode 100644 vendor/texlang/src/types/mathcode.rs create mode 100644 vendor/texlang/src/types/mod.rs create mode 100644 vendor/texlang/src/types/muglue.rs create mode 100644 vendor/texlang/src/variable.rs create mode 100644 vendor/texlang/src/vm/mod.rs create mode 100644 vendor/texlang/src/vm/serde.rs create mode 100644 vendor/texlang/src/vm/streams.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..490cdf5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target/ +/projects/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..fe79890 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1201 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "adler32" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "approx" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0e60b75072ecd4168020818c0107f2857bb6c4e64252d8d3983f6263b40a5c3" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ascii" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base-x" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cbbc9d0964165b47557570cce6c952866c2678457aca742aafc9fb771d30270" + +[[package]] +name = "bincode" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740" +dependencies = [ + "serde", + "unty", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "boxworks" +version = "0.1.0" +source = "git+https://github.com/jamespfennell/texcraft?rev=c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0#c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" +dependencies = [ + "common", +] + +[[package]] +name = "boxworks-knuthplass" +version = "0.1.0" +source = "git+https://github.com/jamespfennell/texcraft?rev=c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0#c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" +dependencies = [ + "boxworks", + "common", +] + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "chunked_transfer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "colored" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "common" +version = "0.1.0" +source = "git+https://github.com/jamespfennell/texcraft?rev=c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0#c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" +dependencies = [ + "serde", +] + +[[package]] +name = "const_fn" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413d67b29ef1021b4d60f4aa1e925ca031751e213832b4b1d588fae623c05c60" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "deflate" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73770f8e1fe7d64df17ca66ad28994a0a623ea497fa69486e14984e715c5d174" +dependencies = [ + "adler32", + "byteorder", +] + +[[package]] +name = "derive_more" +version = "0.99.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "discard" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "212d0f5754cb6769937f4501cc0e67f4f4483c8d2c3e1e922ee9edbe4ab4c7c0" + +[[package]] +name = "dtoa" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56899898ce76aaf4a0f24d914c97ea6ed976d42fec6ad33fcbb0a1103e07b2b0" + +[[package]] +name = "encoding" +version = "0.2.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0d943856b990d12d3b55b359144ff341533e516d94098b1d3fc1ac666d36ec" +dependencies = [ + "encoding-index-japanese", + "encoding-index-korean", + "encoding-index-simpchinese", + "encoding-index-singlebyte", + "encoding-index-tradchinese", +] + +[[package]] +name = "encoding-index-japanese" +version = "1.20141219.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04e8b2ff42e9a05335dbf8b5c6f7567e5591d0d916ccef4e0b1710d32a0d0c91" +dependencies = [ + "encoding_index_tests", +] + +[[package]] +name = "encoding-index-korean" +version = "1.20141219.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dc33fb8e6bcba213fe2f14275f0963fd16f0a02c878e3095ecfdf5bee529d81" +dependencies = [ + "encoding_index_tests", +] + +[[package]] +name = "encoding-index-simpchinese" +version = "1.20141219.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87a7194909b9118fc707194baa434a4e3b0fb6a5a757c73c3adb07aa25031f7" +dependencies = [ + "encoding_index_tests", +] + +[[package]] +name = "encoding-index-singlebyte" +version = "1.20141219.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3351d5acffb224af9ca265f435b859c7c01537c0849754d3db3fdf2bfe2ae84a" +dependencies = [ + "encoding_index_tests", +] + +[[package]] +name = "encoding-index-tradchinese" +version = "1.20141219.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd0e20d5688ce3cab59eb3ef3a2083a5c77bf496cb798dc6fcdb75f323890c18" +dependencies = [ + "encoding_index_tests", +] + +[[package]] +name = "encoding_index_tests" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a246d82be1c9d791c5dfde9a2bd045fc3cbba3fa2b11ad558f27d01712f00569" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "genpdf" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1c422344482708cb32db843cf3f55f27918cd24fec7b505bde895a1e8702c34" +dependencies = [ + "derive_more", + "image", + "lopdf", + "printpdf", + "rusttype", +] + +[[package]] +name = "gif" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3edd93c6756b4dfaf2709eafcc345ba2636565295c198a9cfbf75fa5e3e00b06" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyphenate" +version = "0.1.0" + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "image" +version = "0.23.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24ffcb7e7244a9bf19d35bf2883b9c080c4ced3c07a9895572178cdb8f13f6a1" +dependencies = [ + "bytemuck", + "byteorder", + "color_quant", + "gif", + "jpeg-decoder", + "num-iter", + "num-rational", + "num-traits", + "png", + "tiff", +] + +[[package]] +name = "itoa" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jpeg-decoder" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229d53d58899083193af11e15917b5640cd40b29ff475a1fe4ef725deb02d0f2" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linked-hash-map" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lopdf" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b49a0272112719d0037ab63d4bb67f73ba659e1e90bc38f235f163a457ac16f3" +dependencies = [ + "chrono", + "dtoa", + "encoding", + "flate2", + "itoa 0.4.8", + "linked-hash-map", + "log", + "lzw", + "pom", + "time", +] + +[[package]] +name = "lzw" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d947cbb889ed21c2a84be6ffbaebf5b4e0f4340638cba0444907e38b56be084" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791daaae1ed6889560f8c4359194f56648355540573244a5448a83ba1ecc7435" +dependencies = [ + "adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" +dependencies = [ + "adler", + "autocfg", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12ac428b1cb17fce6f731001d307d351ec70a6d202fc2e60f7d4c5e42d8f4f07" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "ordered-float" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3305af35278dd29f46fcdd139e0b1fbfae2153f0e5928b39b035542dd31e37b7" +dependencies = [ + "num-traits", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "png" +version = "0.16.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3287920cb847dee3de33d301c463fba14dda99db24214ddf93f83d3021f4c6" +dependencies = [ + "bitflags", + "crc32fast", + "deflate", + "miniz_oxide 0.3.7", +] + +[[package]] +name = "pom" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c972d8f86e943ad532d0b04e8965a749ad1d18bb981a9c7b3ae72fe7fd7744b" +dependencies = [ + "bstr", +] + +[[package]] +name = "printpdf" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a2472a184bcb128d0e3db65b59ebd11d010259a5e14fd9d048cba8f2c9302d4" +dependencies = [ + "image", + "js-sys", + "lopdf", + "rusttype", + "time", +] + +[[package]] +name = "proc-macro-hack" +version = "0.5.20+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" + +[[package]] +name = "rmp" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "rmp-serde" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" +dependencies = [ + "rmp", + "serde", +] + +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +dependencies = [ + "semver", +] + +[[package]] +name = "rusttype" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f61411055101f7b60ecf1041d87fb74205fb20b0c7a723f07ef39174cf6b4c0" +dependencies = [ + "approx", + "ordered-float", + "stb_truetype", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "semver" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +dependencies = [ + "semver-parser", +] + +[[package]] +name = "semver-parser" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa 1.0.18", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha1" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" +dependencies = [ + "sha1_smol", +] + +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "standback" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e113fb6f3de07a243d434a56ec6f186dfd51cb08448239fe7bcae73f87ff28ff" +dependencies = [ + "version_check", +] + +[[package]] +name = "stb_truetype" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f77b6b07e862c66a9f3e62a07588fee67cd90a9135a2b942409f195507b4fb51" +dependencies = [ + "byteorder", +] + +[[package]] +name = "stdweb" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d022496b16281348b52d0e30ae99e01a73d737b2f45d38fed4edf79f9325a1d5" +dependencies = [ + "discard", + "rustc_version", + "stdweb-derive", + "stdweb-internal-macros", + "stdweb-internal-runtime", + "wasm-bindgen", +] + +[[package]] +name = "stdweb-derive" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c87a60a40fccc84bef0652345bbbbbe20a605bf5d0ce81719fc476f5c03b50ef" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_derive", + "syn 1.0.109", +] + +[[package]] +name = "stdweb-internal-macros" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58fa5ff6ad0d98d1ffa8cb115892b6e69d67799f6763e162a1c9db421dc22e11" +dependencies = [ + "base-x", + "proc-macro2", + "quote", + "serde", + "serde_derive", + "serde_json", + "sha1", + "syn 1.0.109", +] + +[[package]] +name = "stdweb-internal-runtime" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "texcraft-stdext" +version = "0.1.0" +source = "git+https://github.com/jamespfennell/texcraft?rev=c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0#c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" +dependencies = [ + "colored", + "serde", +] + +[[package]] +name = "texlang" +version = "0.1.0" +dependencies = [ + "common", + "serde", + "texcraft-stdext", + "texrra-core", +] + +[[package]] +name = "texlang-common" +version = "0.1.0" +source = "git+https://github.com/jamespfennell/texcraft?rev=c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0#c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" +dependencies = [ + "texlang", +] + +[[package]] +name = "texlang-stdlib" +version = "0.1.0" +dependencies = [ + "bincode", + "common", + "rmp-serde", + "serde", + "serde_json", + "texcraft-stdext", + "texlang", + "texlang-common", + "texlang-testing", +] + +[[package]] +name = "texlang-testing" +version = "0.1.0" +source = "git+https://github.com/jamespfennell/texcraft?rev=c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0#c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" +dependencies = [ + "bincode", + "rmp-serde", + "serde", + "serde_json", + "texlang", +] + +[[package]] +name = "texrra-core" +version = "0.1.0" +dependencies = [ + "common", + "serde", + "ttf-parser", +] + +[[package]] +name = "texrra-engine" +version = "0.1.0" +dependencies = [ + "boxworks", + "boxworks-knuthplass", + "common", + "flate2", + "genpdf", + "hyphenate", + "image", + "rmp-serde", + "rusttype", + "serde", + "texcraft-stdext", + "texlang", + "texlang-common", + "texlang-stdlib", + "texrra-core", + "tiny_http", + "ttf-parser", +] + +[[package]] +name = "tiff" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a53f4706d65497df0c4349241deddf35f84cee19c87ed86ea8ca590f4464437" +dependencies = [ + "jpeg-decoder", + "miniz_oxide 0.4.4", + "weezl", +] + +[[package]] +name = "time" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4752a97f8eebd6854ff91f1c1824cd6160626ac4bd44287f7f4ea2035a02a242" +dependencies = [ + "const_fn", + "libc", + "standback", + "stdweb", + "time-macros", + "version_check", + "winapi", +] + +[[package]] +name = "time-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "957e9c6e26f12cb6d0dd7fc776bb67a706312e7299aed74c8dd5b17ebb27e2f1" +dependencies = [ + "proc-macro-hack", + "time-macros-impl", +] + +[[package]] +name = "time-macros-impl" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3c141a1b43194f3f56a1411225df8646c55781d5f26db825b3d98507eb482f" +dependencies = [ + "proc-macro-hack", + "proc-macro2", + "quote", + "standback", + "syn 1.0.109", +] + +[[package]] +name = "tiny_http" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82" +dependencies = [ + "ascii", + "chunked_transfer", + "httpdate", + "log", +] + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unty" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..c9cda7e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "texrra-engine" +version = "0.1.0" +edition = "2024" +rust-version = "1.92" +license = "MIT OR Apache-2.0" +description = "Rust-native incremental LaTeX typesetting engine with a live preview server" + +[[bin]] +name = "texrra" +path = "src/main.rs" + +[dependencies] +texrra-core = { path = "crates/texrra-core", features = ["serde"] } +flate2 = "1.1" +hyphenate = { path = "vendor/hyphenate" } +genpdf = { version = "0.2.0", features = ["images"] } +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" } +boxworks-knuthplass = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" } +rusttype = "0.8.3" +texlang = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" } +texlang-stdlib = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0", default-features = false, features = ["serde"] } +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"] } +rmp-serde = "1.3" +tiny_http = "0.12" +ttf-parser = "0.25.1" + +[patch."https://github.com/jamespfennell/texcraft"] +texlang = { path = "vendor/texlang" } +texlang-stdlib = { path = "vendor/texlang-stdlib" } diff --git a/README.md b/README.md new file mode 100644 index 0000000..2169a13 --- /dev/null +++ b/README.md @@ -0,0 +1,442 @@ +# 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. + +## Repository layout + +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 +``` + +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 +`favicon.svg`; preview font faces are generated by the engine at `/fonts.css` +and `/fonts/*.ttf`. + +## Run + +```sh +git clone https://git.iloveuulove.me/gloamxun/texrra-engine.git engine +git clone https://git.iloveuulove.me/gloamxun/texrra-web.git web +cd engine +cargo run --release -- serve examples/hello.tex 4174 +``` + +Open . Without an explicit port the server uses 4173. +`TEXRRA_WEB_DIR` can point at the web checkout when it is not a sibling +directory. + +The server keeps projects in `projects/`; set `TEXRRA_PROJECTS_DIR` to use +another directory. When the projects directory is empty, the input `.tex` file's +directory is imported as the first project, so the sample document is ready to +open. Edits are saved to the file inside the project and recompiled after a +short pause. + +## Project API + +| Endpoint | Purpose | +| --- | --- | +| `GET /api/projects` | Project list with files and metadata | +| `POST /api/projects?name=` | Create a project from a ZIP body | +| `POST /api/projects/new?name=` | Create an empty project | +| `GET /api/projects/` | Project metadata and file list | +| `DELETE /api/projects/` | Delete a project | +| `GET /api/projects//zip` | Download the project as a ZIP | +| `GET /api/projects//raw?path=` | Read a file (`download=1` downloads it) | +| `PUT /api/projects//file?path=` | Write a text file | +| `POST /api/projects//files?path=` | Upload a file | +| `DELETE /api/projects//file?path=` | Delete a file | +| `POST /api/projects//preview` | Live preview of the main file | +| `POST /api/projects//pdf` | PDF of the main file | + +Projects are ordinary directories: + +``` +projects/ + hello/ + hello.tex + plot.png + .meta/hello.meta # display name, main file, timestamps +``` + +The upload path rejects absolute paths and `..`, ignores directory entries, +rejects encrypted and ZIP64 archives, and caps a project at 64 MB / 2000 files. + +## Real-time preview + +The frontend shows the Rust layout result live: + +- Every request lays out the document into the same positioned page frames the + PDF painter consumes, then serializes each page to inline SVG. Text baselines, + line breaks, table rules, image placement, and math boxes therefore match the + PDF instead of being re-approximated by the browser. +- The preview page keeps one `
` per page and replaces only the pages whose + content hash changed, so typing does not reload the whole view, jump the + scroll position, or repaint unchanged pages. +- Fonts are served once from `/fonts.css` and `/fonts/*.ttf` with long-lived + cache headers, so a preview response is only the changed page markup. +- Font faces, font metrics, and the math metrics snapshot stay cached in the + compiler session across requests. A warm edit compiles and transfers in a few + milliseconds for the sample document; set `TEXRRA_TIMING=1` to log the + per-stage timings the server prints. +- The `导出 PDF` button runs the full PDF path and downloads the result. + Documents whose layout still falls back to the `genpdf` page flow report that + the live preview is unavailable instead of showing a partial page. + +The HTTP endpoints are: + +| Endpoint | Purpose | +| --- | --- | +| `GET /`, `/index.html`, `/styles.css`, `/app.js` | Static texrra-web frontend | +| `GET /api/projects...` | Project management API (see above) | +| `GET /fonts.css`, `GET /fonts/*.ttf` | Preview font faces | + +Legacy single-file endpoints are still available for scripting: +`GET /source`, `POST /preview`, `POST /compile`, and `POST /texrra` operate on +the `.tex` file passed to `serve`. + +## Current Rust compiler scope + +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, bold, italic and monospaced text, 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. + +### LaTeX compatibility layer + +Real templates can load local `.sty` files and use the common LaTeX +parameterization commands: + +- `\newif` / `\iffoo` / `\footrue` / `\foofalse` conditionals, including + `\else` and `\fi` branches. +- `\newlength`, `\setlength`, and `\addtolength` (skip registers), plus + `\newcounter` / `\setcounter` / `\addtocounter`. +- `\newcommand`, `\renewcommand`, `\providecommand`, `\def`, `\let`, and + legacy commands such as `\setlength`-style kernel macros. +- `\newenvironment` / `\renewenvironment` are accepted; layout-critical + environments (`abstract`, `figure`, `table`, lists, `tabular`) keep the + engine's native behavior, and redefinitions of the structural commands + (`\section`, `\maketitle`, font-size commands, font family defaults) are + ignored rather than replaced with TeX box code the layout engine cannot run. +- `\AtBeginDocument` bodies run immediately, which lets styles apply + `\newgeometry`. +- Package files are read with `@` as a letter, so `\@title`-style internals + tokenize correctly. + +`\documentclass[options]{class}` parses class options, accepts the built-in +`article`, `report`, `book`, `letter`, `minimal`, and `standalone` classes, and +loads a local `.cls` when one exists. `\DeclareOption`, +`\DeclareOption*`, `\ProcessOptions`, `\ProcessOptions*`, `\ExecuteOptions`, +`\PassOptionsToPackage`, and `\PassOptionsToClass` implement the LaTeX option +protocol, so local classes and packages receive their options (including +options passed before `\usepackage`). Paper-size options (`a4paper`, +`a5paper`, `b5paper`, `letterpaper`, `legalpaper`, `executivepaper`, and +`landscape`) are honored from both the class options and `geometry` +options/`\geometry{...}` settings, including `paperwidth`, `paperheight`, +`textwidth`, and `textheight`. `textwidth` centers the text block and +`textheight` sizes it below the current top margin. The chosen page size drives +the PDF pages, the positioned layout, and the SVG preview. + +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`, +`\doi`, `\lipsum`, `\verb`), and are no-ops where they only affect the PDF +back end (`\hypersetup`, `\fancyhf`, `\microtypesetup`). + +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 +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. + +`\parbox[position]{width}{...}` is a **block box with a fixed width**: the +content is wrapped at `width`, placed in the vertical flow, and painted without +a frame (the optional position argument is parsed but ignored). `\fbox{...}` +remains the framed variant of the same block machinery, and its frame/padding +are applied only when framing is requested. Like `\fbox`, a `\parbox` is an +atomic vertical block rather than an inline object. + +NFSS-style **declarations** are supported with TeX group scoping: +`\bfseries`/`\bf`, `\itshape`/`\slshape`/`\it`, `\ttfamily`/`\tt`, and the +resets `\normalfont`, `\upshape`, `\rmfamily`, `\mdseries`, `\rm`. They stay +active until the end of the current group and nest correctly +(`{\bfseries a {\normalfont b} c}` restores bold for `c`). `\textrm`, `\textup`, `\textmd`, `\textsl`, `\textnormal` are grouped +style commands for roman/upright/medium/slanted/normal text; `\em` is an +italic declaration (an approximation of the LaTeX toggling behaviour). +`\sffamily` is still accepted but does not switch to a sans family. +`\scshape` and `\textsc{...}` are supported as an **uppercase approximation** +(the text is uppercased with unchanged size); real small-caps glyphs and the +usual 80% size reduction are not implemented yet. + +`\mbox{...}` and `\makebox{...}` are **inline horizontal boxes**: the content +is measured as a single unbreakable unit, spaces inside become fixed-width kerns +(no stretching, no line break, and hyphenation is suppressed inside the box), +and nested boxes and inline rules are preserved. Boxes that do not fit on the +current line overflow like an overfull TeX hbox rather than wrapping. + +`\checkmark`, `\textdagger`, `\textdaggerdbl`, `\textperiodcentered`, +`\textsection`, `\textparagraph`, `\textbrokenbar`, and `\textvisiblespace` +expand to `✓ † ‡ · § ¶ ¦ ␣`. `\hfill` is still unsupported (the line breaker +does not stretch infinite glue on the last line). + +Numeric/unit symbols `\textperthousand`, `\textonehalf`, `\textonequarter`, +`\textthreequarters`, `\textonesuperior`, `\texttwosuperior`, +`\textthreesuperior`, `\textordfeminine`, `\textordmasculine`, `\textohm`, +and `\textcelsius` expand to `‰ ½ ¼ ¾ ¹ ² ³ ª º Ω °C`. + +Typographic/currency symbols `\textasciitilde`, `\textasciicircum`, +`\textless`, `\textgreater`, `\textbar`, `\textunderscore`, +`\guillemotleft`, `\guillemotright`, `\textquotesingle`, `\texteuro`, +`\textsterling`, `\textyen`, `\textcent`, `\textdegree`, `\textpm`, and +`\textmu` expand to their Unicode characters. + +Letter macros `\ss`, `\ae`, `\AE`, `\oe`, `\OE`, `\aa`, `\AA`, `\o`, `\O`, +`\l`, `\L`, and `\i` expand to their Unicode letters. + +Text punctuation macros `\ldots`, `\dots`, `\textendash`, `\textemdash`, +`\textquoteleft`, `\textquoteright`, `\textquotedblleft`, and +`\textquotedblright` expand to their Unicode characters. + +Text symbols `\S`, `\P`, `\dag`, `\ddag`, `\copyright`, `\textbullet`, +`\textregistered`, and `\texttrademark` expand to their Unicode characters +(`§ ¶ † ‡ © • ® ™`). + +`\linebreak`, `\nolinebreak`, `\nopagebreak`, and `\samepage` are accepted +(their optional `[penalty]` argument is consumed) as advisory no-ops: line and +page breaking stay automatic, and forced breaks continue to use `\\` and +`\newpage`. + +`\thinspace` (1/6em), `\negthinspace`, `\enspace` (1/2em), `\medspace` +(2/9em), `\negmedspace`, `\thickspace` (5/18em), and `\negthickspace` are +horizontal skips, so they produce real gaps in text (previously `\enspace` was +an ordinary space and the others were undefined). + +`\quad` and `\qquad` are horizontal skips of 1em and 2em, so they produce real +gaps in text as well as in math (previously they were math-space events that +collapsed to an ordinary space in text). + +`\vspace` and `\hspace` are primitives that accept both the braced form and +the starred form (`\vspace*{12pt}`, `\hspace*{1cm}`); the star is consumed and +the dimension is passed to `\vskip`/`\hskip`. + +`\textwidth` (160mm), `\textheight` (247mm), `\linewidth`, and +`\columnwidth` are provided as fixed defaults for the A4 content box, so +`\parbox{\textwidth}` and `\rule{\textwidth}{1pt}` work; they are not +geometry-aware yet (a changed page size or margin keeps these defaults). + +`\smallbreak`, `\medbreak`, `\bigbreak` add the corresponding skip (the +encouraged page break itself is not inserted yet). `\tableofcontents`, +`\listoffigures`, and `\listoftables` are accepted as no-ops because contents +lists are not generated yet. + +Vertical skips are active: `\smallskip`, `\medskip`, and `\bigskip` map to +3pt/6pt/12pt `\vskip` glue, and `\addvspace{...}` forwards its argument to +`\vskip` (ordinary `\vspace{...}` already did). + +`\hrule` is a full-width block rule (0.4pt high by default): it occupies its +own vertical slot, paints a filled rectangle in the PDF and SVG preview, and is +separated from surrounding paragraphs like a normal block. The plain-TeX +`height` and `width` arguments are parsed (`\hrule height 6pt`, +`\hrule width 60mm height 2pt`); without a width the rule spans the text +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. + +`\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 +rule reserves space without painting ink. `\fbox{...}` is a block-level framed +box: the content is measured as a single line, wrapped in 3pt padding and a +0.4pt frame, placed in the vertical flow, and painted in both the PDF and the +SVG preview. Inline `\fbox` in the middle of a paragraph starts a new block +(this is a stepping stone towards full inline boxes). + +Known gaps for full document classes: base font-size class options +(`10pt`/`11pt`/`12pt`) are parsed but the engine still uses 11pt; footnotes and +`\thanks` are dropped, +custom `\maketitle` implementations are ignored (the engine title layout is +used), `\raisebox` and `\minipage` are not implemented yet, inline `\fbox` +still starts a block instead of an inline frame, `\parbox` is block-level +rather than inline, and the abstract prints as body text without an +"Abstract" heading. + +Basic `\input{file}` imports are read relative to the main `.tex` file. Imported +files participate in source mapping and frontend cache invalidation. Local style +files and `.bib` files are tracked the same way; editing any of them refreshes +the TeX expansion and preview model. + +The Rust backend recognizes a compatibility subset of `geometry`, `graphicx`, +`amsmath`, `amssymb`, `booktabs`, `hyperref`, `cite`, `natbib`, `inputenc`, and +`fontenc`. The Rust TeX VM handles `\usepackage` and `\RequirePackage` in input +order. It loads local `.sty` files from the importing file's directory, the +main `.tex` directory, or directories listed in `TEXRRA_STY_DIR` (use the +platform path separator for multiple directories). A local style can use +`\def`, `\newcommand`, `\renewcommand`, and `\providecommand` to define macros; +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. + +`\includegraphics` embeds PNG, JPEG, or BMP files relative to the `.tex` file. +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` +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, page-number references, and automatic table of +contents are not implemented. + +Boxworks' Knuth–Plass line breaker lays out ordinary text paragraphs with the +same Latin, CJK, and monospaced font faces used by the PDF renderer, including +bold and italic variants, and applies font pair kerning to line-break widths. +It adds breakpoints between CJK characters and observes basic punctuation +restrictions. Unchanged plain-text paragraph line breaks are reused between +edits; source expansion, +parsing, and PDF export still run for the full document. Paragraphs with inline +math and wide display equations use the Knuth–Plass pass: words break at spaces +and top-level math sequences expose penalized breakpoints after relations, +binary operators, and punctuation. Fractions, scripts, roots, and delimiters +remain indivisible math boxes. Rust paints ordinary paragraph lines at their +measured baselines and applies the line breaker's adjusted word spaces. For +documents with no title block and only plain paragraphs and headings, Rust +builds the vertical list, chooses page breaks, and assigns line positions; +`genpdf` paints those line boxes at the planned coordinates. Mixed-content +documents still use `genpdf` for page composition. This fixed-spacing subset is +an initial page-building slice, not full TeX page building. Display math +preserves stacked fractions, indexed radicals, scripts, and math atom classes +in its expression tree. PDF layout applies TeX's class spacing rules, stacks +display limits for common large operators, draws fraction bars and root bars, +and supports explicit math spaces. Radical signs use vertical OpenType MATH +variants or assemblies when the metrics face provides them. A metrics face +with an OpenType MATH table also supplies the axis height, fraction, script, +radical-degree, display-limit, and vertical and horizontal glyph construction +data. The compiler searches common TeX Live paths for STIX Two Math, New +Computer Modern Math, then STIX Math. Set +`TEXRRA_MATH_METRICS_FONT` to a TrueType or OpenType font with a MATH table to +select another face; a configured font without the table is reported as an +error. + +Local math font files can be assigned to TeX's family registers. Paths resolve +relative to the `.tex` file: + +```tex +\font\mathface=fonts/Math-Regular.ttf +\textfont1=\mathface +\scriptfont1=\mathface +\scriptscriptfont1=\mathface +``` + +This selects the face for ordinary glyphs in family 1 at text, script, and +scriptscript sizes. Assignments respect TeX grouping, and PDF and SVG use the +same glyph outline. `\\Uradical` and `\\Udelimiter` also select their glyph +variants and assemblies from the requested family; `\\Umathaccent` selects +the accent glyph and horizontal construction from its family. Glyph-based +standard accents such as `\\hat`, `\\widehat`, and `\\overbrace` use the +current math family's font at the active style size. Regular text shaping is +still incomplete. Classic `\\left...\\right` delimiters use `\\delcode` to select +their small and large math families. Family assignments at text, script, and +scriptscript sizes carry through to both PDF and SVG output. +`\\left...\\right` selects the +smallest available vertical glyph +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. +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 +glyph image. A loaded MATH face supplies operators, relations, delimiters, Unicode +Greek letters, and other single-symbol atoms. Default math-italic Latin letters +also use that face when the glyph is available; bold, roman, and text styles use +the corresponding Liberation Serif face. Lowercase Greek letters use the +italic math family, while uppercase Greek letters use the current math family, +following TeX's default mathcode behavior. Unavailable or non-outline glyphs use +the text fallback. +Without a MATH font, the compiler keeps the size-scaling fallback. Basic +single-glyph subscript and superscript pairs use OpenType `MathKernInfo` when +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. +`matrix`, `pmatrix`, `bmatrix`, +`Bmatrix`, `vmatrix`, `Vmatrix`, `cases`, `aligned`, `gathered`, `multline`, and +`array` environments build a two-dimensional math grid. Matrix delimiters are +drawn around the grid, and `array` reads simple `l`, `c`, and `r` column specs. The +unstarred `equation`, `align`, `alignat`, `flalign`, `eqnarray`, `gather`, and +`multline` environments support equation numbers, `\label`, `\tag`, `\nonumber`, +`\tag*`, `\notag`, and `\ref`. Alignment environments number rows independently; +`multline` uses the full text width and has one number aligned with its final +row. PDF and HTML preview use the same math row layout. This +is a supported subset, not full `amsmath` behavior or OpenType math shaping for +ordinary symbols and operators. Other unsupported TeX commands are reported as +compile errors. + +The default font paths cover common Linux installations. Set +`TEXRRA_FONT_DIR` to a directory containing `LiberationSerif-Regular.ttf`, +`LiberationSerif-Bold.ttf`, `LiberationSerif-Italic.ttf`, and +`LiberationSerif-BoldItalic.ttf` if the fonts are elsewhere. For CJK output, +set `TEXRRA_CJK_FONT` to a TrueType font file with the required glyphs when +the system fallback cannot be found. For `\texttt` output, set +`TEXRRA_MONO_FONT_DIR` when Liberation Mono is not in a common Linux font +directory. + +## Experimental HTML endpoint + +The `/texrra` endpoint remains available for inspecting the Rust parser's +document model; it uses browser flow layout rather than the positioned page +frames. The editor preview uses the live SVG pages described above, and the PDF +export uses the same frames. + +## Box material example + +`examples/boxes.tex` exercises the box material in one document: `\fbox`, +inline `\mbox`, `\parbox`, the `center` environment, `\hrule`, vertical skips, +and the NFSS style declarations. + +## Compatibility example + +`examples/compat.tex` collects the accumulated compatibility layer in one +document: spacing macros, symbols and letters, NFSS declarations, small caps, +advisory breaks, starred `\vspace`/`\hspace`, `center`, `\hrule`, `\fbox`, +`\mbox`, and `\parbox`. + +## Capability matrix (current) + +| Area | Implemented | Remaining | +| --- | --- | --- | +| Boxes | `\rule`, `\fbox`, `\parbox`, inline `\mbox`/`\makebox`, `center`, `\hrule` | inline framed `\fbox`, `\raisebox`, `\minipage`, VBox | +| Fonts | serif/mono faces, bold/italic/mono declarations, group scoping, uppercase small caps | `\sffamily` (sans face), real small-cap glyphs | +| Paragraphs | Knuth-Plass breaking, TeX hyphenation, justification, centering | explicit indentation (`\parindent`) | +| Notes/floats | — | footnote insertion area, figure/table floats | +| Pages | A4/Letter/... page sizes, margins/geometry, automatic pagination, `\newpage`, `\pagebreak` | headers/footers (`fancyhdr`), unified planner/renderer | +| Classes/packages | built-in + local classes, option protocol, local package options | base font-size options (10/11/12pt) | +| Live preview | incremental paragraph/page caches, 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. diff --git a/crates/texrra-core/Cargo.toml b/crates/texrra-core/Cargo.toml new file mode 100644 index 0000000..0521018 --- /dev/null +++ b/crates/texrra-core/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "texrra-core" +version = "0.1.0" +edition = "2024" +license = "MIT" +description = "TeX token, state, input, and value core for the Rust engine" + +[dependencies] +common = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" } +ttf-parser = "0.25.1" +serde = { version = "1.0", features = ["derive"], optional = true } + +[features] +default = [] +serde = ["dep:serde", "common/serde"] diff --git a/crates/texrra-core/src/assignment_scope.rs b/crates/texrra-core/src/assignment_scope.rs new file mode 100644 index 0000000..98a78f6 --- /dev/null +++ b/crates/texrra-core/src/assignment_scope.rs @@ -0,0 +1,85 @@ +/// Assignment scope selected by TeX prefixes and `\\globaldefs`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum AssignmentScopeKind { + Local, + Global, +} + +impl Default for AssignmentScopeKind { + fn default() -> Self { + Self::Local + } +} + +#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] +pub struct AssignmentScope { + global_defs: i32, + global_prefix_pending: bool, + long_prefix_pending: bool, + outer_prefix_pending: bool, + groups: Vec, +} + +#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] +struct AssignmentScopeGroup { + global_defs: Option, +} + +impl AssignmentScope { + pub fn global_defs(&self) -> &i32 { + &self.global_defs + } + + pub fn request_prefixes(&mut self, global: bool, long: bool, outer: bool) { + self.global_prefix_pending |= global; + self.long_prefix_pending |= long; + self.outer_prefix_pending |= outer; + } + + pub fn take_prefixed_scope(&mut self) -> AssignmentScopeKind { + if std::mem::take(&mut self.global_prefix_pending) { + AssignmentScopeKind::Global + } else { + AssignmentScopeKind::Local + } + } + + pub fn take_macro_prefixes(&mut self) -> (bool, bool) { + ( + std::mem::take(&mut self.long_prefix_pending), + std::mem::take(&mut self.outer_prefix_pending), + ) + } + + pub fn global_defs_mut(&mut self, global: bool) -> &mut i32 { + if global { + for group in &mut self.groups { + group.global_defs = None; + } + } else if let Some(group) = self.groups.last_mut() { + group.global_defs.get_or_insert(self.global_defs); + } + &mut self.global_defs + } + + pub fn override_scope(&self, requested: AssignmentScopeKind) -> AssignmentScopeKind { + match self.global_defs.cmp(&0) { + std::cmp::Ordering::Less => AssignmentScopeKind::Local, + std::cmp::Ordering::Equal => requested, + std::cmp::Ordering::Greater => AssignmentScopeKind::Global, + } + } + + pub fn begin_group(&mut self) { + self.groups.push(AssignmentScopeGroup::default()); + } + + pub fn end_group(&mut self) { + let Some(group) = self.groups.pop() else { + return; + }; + if let Some(global_defs) = group.global_defs { + self.global_defs = global_defs; + } + } +} diff --git a/crates/texrra-core/src/command.rs b/crates/texrra-core/src/command.rs new file mode 100644 index 0000000..72aceed --- /dev/null +++ b/crates/texrra-core/src/command.rs @@ -0,0 +1,116 @@ +use std::collections::HashMap; + +use crate::EngineCommandName; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum NativePrimitive { + ParagraphBreak, + LineBreak, + PageBreak, + Penalty, + Kern, + HorizontalSkip, + VerticalSkip, + Advance, + Multiply, + Divide, + Global, + Long, + Outer, + Relax, +} + +/// Meaning selected by the Rust engine for a control sequence. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EngineCommandMeaning { + Macro, + Native(NativePrimitive), +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct NativeCommandTable { + meanings: HashMap, + groups: Vec>>, +} + +impl Default for NativeCommandTable { + fn default() -> Self { + let meanings = [ + ("advance", NativePrimitive::Advance), + ("multiply", NativePrimitive::Multiply), + ("divide", NativePrimitive::Divide), + ("global", NativePrimitive::Global), + ("long", NativePrimitive::Long), + ("outer", NativePrimitive::Outer), + ("relax", NativePrimitive::Relax), + ("par", NativePrimitive::ParagraphBreak), + ("newline", NativePrimitive::LineBreak), + ("texrrapagebreak", NativePrimitive::PageBreak), + ("penalty", NativePrimitive::Penalty), + ("kern", NativePrimitive::Kern), + ("hskip", NativePrimitive::HorizontalSkip), + ("vskip", NativePrimitive::VerticalSkip), + ] + .into_iter() + .map(|(name, primitive)| { + ( + EngineCommandName::ControlSequence(name.to_string()), + primitive, + ) + }) + .collect(); + + Self { + meanings, + groups: Vec::new(), + } + } +} + +impl NativeCommandTable { + pub fn get(&self, name: &EngineCommandName) -> Option { + self.meanings.get(name).copied() + } + + pub fn define(&mut self, name: EngineCommandName, primitive: NativePrimitive, global: bool) { + self.prepare_assignment(&name, global); + self.meanings.insert(name, primitive); + } + + pub fn remove(&mut self, name: EngineCommandName, global: bool) { + self.prepare_assignment(&name, global); + self.meanings.remove(&name); + } + + pub fn begin_group(&mut self) { + self.groups.push(HashMap::new()); + } + + pub fn end_group(&mut self) { + let Some(group) = self.groups.pop() else { + return; + }; + for (name, previous) in group { + match previous { + Some(primitive) => { + self.meanings.insert(name, primitive); + } + None => { + self.meanings.remove(&name); + } + } + } + } + + fn prepare_assignment(&mut self, name: &EngineCommandName, global: bool) { + if global { + for group in &mut self.groups { + group.remove(name); + } + } else if let Some(group) = self.groups.last_mut() { + group + .entry(name.clone()) + .or_insert_with(|| self.meanings.get(name).copied()); + } + } +} diff --git a/crates/texrra-core/src/document.rs b/crates/texrra-core/src/document.rs new file mode 100644 index 0000000..a621f82 --- /dev/null +++ b/crates/texrra-core/src/document.rs @@ -0,0 +1,279 @@ +use std::{ + collections::{HashMap, HashSet}, + path::PathBuf, +}; + +use crate::{TeXGlue, math_expr::MathExpr, source::SourceLocation}; + +/// Physical page dimensions in millimetres. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PageSize { + pub width_mm: f64, + pub height_mm: f64, +} + +impl PageSize { + pub const A4: Self = Self { + width_mm: 210.0, + height_mm: 297.0, + }; + pub const A5: Self = Self { + width_mm: 148.0, + height_mm: 210.0, + }; + pub const B5: Self = Self { + width_mm: 176.0, + height_mm: 250.0, + }; + /// US letter, 8.5 by 11 inches. + pub const LETTER: Self = Self { + width_mm: 215.9, + height_mm: 279.4, + }; + /// US legal, 8.5 by 14 inches. + pub const LEGAL: Self = Self { + width_mm: 215.9, + height_mm: 355.6, + }; + /// US executive, 7.25 by 10.5 inches. + pub const EXECUTIVE: Self = Self { + width_mm: 184.15, + height_mm: 266.7, + }; + + pub fn landscape(self) -> Self { + Self { + width_mm: self.height_mm, + height_mm: self.width_mm, + } + } +} + +impl Default for PageSize { + fn default() -> Self { + Self::A4 + } +} + +#[derive(Clone, Default)] +pub struct DocumentModel { + pub title: String, + pub author: String, + pub date: String, + pub page: PageSize, + pub margins: PageMargins, + pub show_title: bool, + pub blocks: Vec, + pub block_sources: Vec>, + pub labels: HashMap, + pub citations: HashMap, +} + +pub struct ParsedDocument(pub DocumentModel); + +#[derive(Clone)] +pub struct PageMargins { + pub top: f64, + pub right: f64, + pub bottom: f64, + pub left: f64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct EquationNumber { + pub text: String, + pub parenthesized: bool, +} + +impl Default for PageMargins { + fn default() -> Self { + Self { + top: 25.0, + right: 25.0, + bottom: 25.0, + left: 25.0, + } + } +} + +#[derive(Clone)] +pub enum Block { + Paragraph(Vec), + Heading { + level: u8, + runs: Vec, + }, + List(ListBlock), + Table { + rows: Vec>>, + caption: Option>, + alignments: Vec, + rules: Vec, + }, + Image { + path: String, + options: String, + caption: Option>, + }, + Bibliography(Vec<(String, Vec)>), + /// A box such as `\fbox{...}` (framed) or `\parbox{width}{...}`. + FramedBox { + runs: Vec, + frame: bool, + width: Option, + }, + /// Center-aligned content produced by the `center` environment. + Centered { + runs: Vec, + }, + /// A horizontal rule such as `\hrule` (full width when `width` is None). + HorizontalRule { + height: common::Scaled, + width: Option, + }, + Math { + expression: MathExpr, + equation_numbers: Vec>, + }, + VerticalKern(common::Scaled), + VerticalGlue(TeXGlue), + Penalty(i32), + PageBreak, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ColumnAlignment { + Left, + Center, + Right, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct ListBlock { + pub ordered: bool, + pub items: Vec, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct ListItem { + pub runs: Vec, + pub nested: Vec, + pub vertical_glue_after: Vec, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub enum UnresolvedReference { + Label(String), + Citation(Vec), +} + +/// An unbreakable inline box such as `\mbox{...}` or `\makebox{...}`. +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct InlineBox { + pub runs: Vec, +} + +/// A filled rectangle produced by `\rule`. +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct RuleBox { + pub width: common::Scaled, + /// Distance from the baseline to the bottom edge of the ink. + /// + /// A positive raise leaves a gap between the baseline and the rule; a + /// negative raise moves the rule below the baseline. + pub raise: common::Scaled, + /// Thickness of the rule. + pub height: common::Scaled, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Run { + pub text: String, + pub math: Option, + pub kern: Option, + pub glue: Option, + pub penalty: Option, + pub rule: Option, + pub box_run: Option, + pub unresolved_reference: Option, + pub bold: bool, + pub italic: bool, + pub monospace: bool, +} + +impl Run { + pub fn plain(text: String) -> Self { + Self { + text, + math: None, + kern: None, + glue: None, + penalty: None, + rule: None, + box_run: None, + unresolved_reference: None, + bold: false, + italic: false, + monospace: false, + } + } +} + +impl DocumentModel { + pub fn math_font_files(&self) -> HashSet { + fn collect_runs(runs: &[Run], files: &mut HashSet) { + for run in runs { + if let Some(expression) = &run.math { + expression.collect_math_font_files(files); + } + } + } + + fn collect_list(list: &ListBlock, files: &mut HashSet) { + for item in &list.items { + collect_runs(&item.runs, files); + for nested in &item.nested { + collect_list(nested, files); + } + } + } + + let mut files = HashSet::new(); + for block in &self.blocks { + match block { + Block::Paragraph(runs) | Block::Heading { runs, .. } => { + collect_runs(runs, &mut files); + } + Block::List(list) => collect_list(list, &mut files), + Block::Table { rows, caption, .. } => { + for cell in rows.iter().flatten() { + collect_runs(cell, &mut files); + } + if let Some(caption) = caption { + collect_runs(caption, &mut files); + } + } + Block::Image { caption, .. } => { + if let Some(caption) = caption { + collect_runs(caption, &mut files); + } + } + Block::FramedBox { runs, .. } | Block::Centered { runs } => { + collect_runs(runs, &mut files); + } + Block::Bibliography(items) => { + for (_, runs) in items { + collect_runs(runs, &mut files); + } + } + Block::Math { expression, .. } => expression.collect_math_font_files(&mut files), + Block::HorizontalRule { .. } + | Block::VerticalKern(_) + | Block::VerticalGlue(_) + | Block::Penalty(_) + | Block::PageBreak => {} + } + } + files + } +} diff --git a/crates/texrra-core/src/document_parser.rs b/crates/texrra-core/src/document_parser.rs new file mode 100644 index 0000000..838392c --- /dev/null +++ b/crates/texrra-core/src/document_parser.rs @@ -0,0 +1,1717 @@ +use std::collections::{HashMap, VecDeque}; + +use crate::{ + TeXGlue, + document::{ + Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, ListBlock, ListItem, + PageMargins, PageSize, ParsedDocument, RuleBox, Run, UnresolvedReference, + }, + expanded, + math_expr::*, + source::SourceLocation, +}; + +#[derive(Default)] +struct ListBuilder { + ordered: bool, + items: Vec, + current: Vec, + nested: Vec, + vertical_glue_after: Vec, + has_current_item: bool, +} + +impl ListBuilder { + fn finish_current_item(&mut self) { + trim_run_end(&mut self.current); + if self.has_current_item + || !self.current.is_empty() + || !self.nested.is_empty() + || !self.vertical_glue_after.is_empty() + { + self.items.push(ListItem { + runs: std::mem::take(&mut self.current), + nested: std::mem::take(&mut self.nested), + vertical_glue_after: std::mem::take(&mut self.vertical_glue_after), + }); + } + self.has_current_item = false; + } +} + +#[derive(Default)] +struct TableBuilder { + rows: Vec>>, + row: Vec>, + cell: Vec, + caption: Option>, + alignments: Vec, + rules: Vec, +} + +#[derive(Default)] +struct BibliographyBuilder { + items: Vec<(String, Vec)>, + current: Option<(String, Vec)>, +} + +struct HeadingBuilder { + level: u8, + runs: Vec, + source: Option, +} + +#[derive(Default)] +pub struct ParagraphParseCache { + entries: HashMap>, + insertion_order: VecDeque, + rich_entries: HashMap>, + rich_insertion_order: VecDeque, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +struct RichParagraphCacheKey { + items: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +struct RichParagraphItemKey { + position: usize, + end_position: usize, + kind: expanded::ExpandedItemKind, + math_code: Option, + math_family: Option, + delimiter_settings: Option, + math_fonts: MathFontFamilies, + math_line_break_penalties: MathLineBreakPenalties, +} + +struct RichParagraphCandidate { + end_index: usize, + key: RichParagraphCacheKey, + source: SourceLocation, + end_source: SourceLocation, + block_index: usize, + math_expressions: Vec, +} + +impl ParagraphParseCache { + fn parse(&mut self, source: &str) -> Vec { + if let Some(runs) = self.entries.get(source) { + return runs.clone(); + } + + let normalized = normalize_whitespace(source); + let text = normalized.trim().to_string(); + let runs = if text.is_empty() { + Vec::new() + } else { + vec![Run::plain(text)] + }; + const CAPACITY: usize = 2048; + if !self.entries.contains_key(source) { + if self.entries.len() == CAPACITY + && let Some(oldest) = self.insertion_order.pop_front() + { + self.entries.remove(&oldest); + } + self.insertion_order.push_back(source.to_string()); + } + self.entries.insert(source.to_string(), runs.clone()); + runs + } + + fn get_rich( + &mut self, + key: &RichParagraphCacheKey, + math_expressions: &[MathExpr], + ) -> Option> { + let mut runs = self.rich_entries.get(key)?.clone(); + let mut math_expressions = math_expressions.iter(); + for run in &mut runs { + if let Some(expression) = &mut run.math { + *expression = math_expressions.next()?.clone(); + } + } + if math_expressions.next().is_some() { + return None; + } + if let Some(index) = self + .rich_insertion_order + .iter() + .position(|cached| cached == key) + { + let key = self + .rich_insertion_order + .remove(index) + .expect("rich paragraph cache index was found"); + self.rich_insertion_order.push_back(key); + } + Some(runs) + } + + fn insert_rich(&mut self, key: RichParagraphCacheKey, runs: Vec) { + const CAPACITY: usize = 256; + if let Some(index) = self + .rich_insertion_order + .iter() + .position(|cached| cached == &key) + { + self.rich_insertion_order.remove(index); + } else if self.rich_entries.len() == CAPACITY + && let Some(oldest) = self.rich_insertion_order.pop_front() + { + self.rich_entries.remove(&oldest); + } + self.rich_insertion_order.push_back(key.clone()); + self.rich_entries.insert(key, runs); + } +} + +fn append_token_text(item: &expanded::ExpandedItem, output: &mut String) { + let expanded::ExpandedItemKind::Token(value) = &item.kind else { + return; + }; + if let Some(character) = value.character() { + output.push(character); + } else if let expanded::ExpandedTokenValue::ControlSequence(name) = value { + output.push('\\'); + output.push_str(name); + } +} + +fn rich_item_key(item: &expanded::ExpandedItem, paragraph_start: usize) -> RichParagraphItemKey { + let kind = match &item.kind { + expanded::ExpandedItemKind::Event(expanded::FrontendEventKind::InlineMath(expression)) => { + expanded::ExpandedItemKind::Event(expanded::FrontendEventKind::InlineMath( + expression.without_source(), + )) + } + kind => kind.clone(), + }; + RichParagraphItemKey { + position: item.position - paragraph_start, + end_position: item.end_position - paragraph_start, + kind, + math_code: item.math_code, + math_family: item.math_family, + delimiter_settings: item.delimiter_settings, + math_fonts: std::sync::Arc::clone(&item.math_fonts), + math_line_break_penalties: item.math_line_break_penalties, + } +} + +fn rich_math_expressions(items: &[expanded::ExpandedItem]) -> Vec { + items + .iter() + .filter_map(|item| match &item.kind { + expanded::ExpandedItemKind::Event(expanded::FrontendEventKind::InlineMath( + expression, + )) if !expression.plain_text().is_empty() => Some(expression.clone()), + _ => None, + }) + .collect() +} + +fn rich_paragraph_candidate( + expanded: &expanded::ExpandedTokenStream, + start_index: usize, + block_index: usize, +) -> Option { + use expanded::{ExpandedItemKind, ExpandedTokenValue, FrontendEventKind as Event}; + + let mut group_depth = 0usize; + let mut has_content = false; + let mut has_rich_event = false; + let mut source = None; + for (index, item) in expanded.items.iter().enumerate().skip(start_index) { + match &item.kind { + ExpandedItemKind::Token(ExpandedTokenValue::ControlSequence(_)) => return None, + ExpandedItemKind::Token(_) => { + has_content = true; + source.get_or_insert_with(|| item.location.clone()); + } + ExpandedItemKind::Event(kind) => match kind { + Event::ParagraphBreak => { + if group_depth != 0 || !has_content || !has_rich_event { + return None; + } + let items = &expanded.items[start_index..=index]; + let paragraph_start = items.first()?.position; + return Some(RichParagraphCandidate { + end_index: index + 1, + key: RichParagraphCacheKey { + items: items + .iter() + .map(|item| rich_item_key(item, paragraph_start)) + .collect(), + }, + source: source?, + end_source: item.location.clone(), + block_index, + math_expressions: rich_math_expressions(items), + }); + } + Event::GroupStart => group_depth += 1, + Event::GroupEnd => { + group_depth = group_depth.checked_sub(1)?; + } + Event::InlineMath(_) + | Event::Reference(_) + | Event::Citation(_) + | Event::LiteralAmpersand + | Event::LiteralCharacter(_) + | Event::LineBreak + | Event::MathCell + | Event::MathSpace(_) + | Event::RowBreak => { + has_content = true; + has_rich_event = true; + source.get_or_insert_with(|| item.location.clone()); + } + _ => return None, + }, + } + } + + if group_depth != 0 || !has_content || !has_rich_event { + return None; + } + let items = &expanded.items[start_index..]; + let paragraph_start = items.first()?.position; + let end_source = expanded.items.last()?.location.clone(); + Some(RichParagraphCandidate { + end_index: expanded.items.len(), + key: RichParagraphCacheKey { + items: items + .iter() + .map(|item| rich_item_key(item, paragraph_start)) + .collect(), + }, + source: source?, + end_source, + block_index, + math_expressions: rich_math_expressions(items), + }) +} + +fn consume_environment_preamble( + expanded: &expanded::ExpandedTokenStream, + start_index: usize, + environment: &str, +) -> usize { + use expanded::{ExpandedItemKind, ExpandedTokenValue, FrontendEventKind as Event}; + + let mut argument_start = start_index; + while let Some(item) = expanded.items.get(argument_start) { + if matches!( + &item.kind, + ExpandedItemKind::Token(ExpandedTokenValue::Space(character)) + if character.is_whitespace() + ) { + argument_start += 1; + } else { + break; + } + } + + if environment == "thebibliography" { + let Some(ExpandedItemKind::Event(Event::GroupStart)) = + expanded.items.get(argument_start).map(|item| &item.kind) + else { + return start_index; + }; + let mut depth = 0usize; + for (index, item) in expanded.items.iter().enumerate().skip(argument_start) { + match &item.kind { + ExpandedItemKind::Event(Event::GroupStart) => depth += 1, + ExpandedItemKind::Event(Event::GroupEnd) => { + depth -= 1; + if depth == 0 { + return index + 1; + } + } + _ => {} + } + } + return start_index; + } + + if !matches!(environment, "figure" | "table") + || expanded + .items + .get(argument_start) + .and_then(|item| match &item.kind { + ExpandedItemKind::Token(value) => value.character(), + ExpandedItemKind::Event(_) => None, + }) + != Some('[') + { + return start_index; + } + + let mut bracket_depth = 0usize; + let mut group_depth = 0usize; + for (index, item) in expanded.items.iter().enumerate().skip(argument_start) { + match &item.kind { + ExpandedItemKind::Event(Event::GroupStart) => group_depth += 1, + ExpandedItemKind::Event(Event::GroupEnd) => { + group_depth = group_depth.saturating_sub(1); + } + ExpandedItemKind::Token(value) if group_depth == 0 => match value.character() { + Some('[') => bracket_depth += 1, + Some(']') => { + bracket_depth = bracket_depth.saturating_sub(1); + if bracket_depth == 0 { + return index + 1; + } + } + _ => {} + }, + _ => {} + } + } + start_index +} + +struct Parser { + document: DocumentModel, + paragraph: Vec, + heading: Option, + lists: Vec, + table: Option, + bibliography: Option, + bold: bool, + italic: bool, + monospace: bool, + small_caps: bool, + text_style_stack: Vec<(expanded::TextStyle, bool, bool, bool, bool)>, + style_declarations: Vec<(usize, expanded::TextStyle)>, + group_depth: usize, + section_numbers: [u32; 3], + equation_number: u32, + figure_number: u32, + table_number: u32, + current_reference: String, + figure_active: bool, + figure_image: Option, + table_active: bool, + current_table_block: Option, + pending_table_caption: Option>, + caption_capture: Option>, + metadata_capture: Option<(expanded::MetadataField, Vec)>, + framed_box: Option>, + box_frame: bool, + box_width: Option, + inline_boxes: Vec>, + centered: Option>, + current_source: Option, + paragraph_source: Option, +} + +impl Parser { + fn new() -> Self { + Self { + document: DocumentModel::default(), + paragraph: Vec::new(), + heading: None, + lists: Vec::new(), + table: None, + bibliography: None, + bold: false, + italic: false, + monospace: false, + small_caps: false, + text_style_stack: Vec::new(), + style_declarations: Vec::new(), + group_depth: 0, + section_numbers: [0; 3], + equation_number: 0, + figure_number: 0, + table_number: 0, + current_reference: String::new(), + figure_active: false, + figure_image: None, + table_active: false, + current_table_block: None, + pending_table_caption: None, + caption_capture: None, + metadata_capture: None, + framed_box: None, + box_frame: true, + box_width: None, + inline_boxes: Vec::new(), + centered: None, + current_source: None, + paragraph_source: None, + } + } + + fn parse( + mut self, + expanded: &expanded::ExpandedTokenStream, + paragraph_cache: &mut ParagraphParseCache, + ) -> ParsedDocument { + let mut pending_text = String::new(); + let mut pending_source = None; + let mut item_index = 0; + let mut rich_candidate = None; + let mut cache_scan_pending = true; + while let Some(item) = expanded.items.get(item_index) { + if cache_scan_pending + && rich_candidate.is_none() + && pending_text.is_empty() + && self.can_reuse_plain_paragraph() + { + cache_scan_pending = false; + if let Some(candidate) = + rich_paragraph_candidate(expanded, item_index, self.document.blocks.len()) + { + if let Some(runs) = + paragraph_cache.get_rich(&candidate.key, &candidate.math_expressions) + { + self.push_block_at(Block::Paragraph(runs), Some(candidate.source)); + self.current_source = Some(candidate.end_source); + item_index = candidate.end_index; + cache_scan_pending = true; + continue; + } + rich_candidate = Some(candidate); + } + } + + match &item.kind { + expanded::ExpandedItemKind::Token(_) => { + if pending_text.is_empty() { + pending_source = Some(item.location.clone()); + } + append_token_text(item, &mut pending_text); + item_index += 1; + } + expanded::ExpandedItemKind::Event(kind) => { + let paragraph_break = + matches!(kind, expanded::FrontendEventKind::ParagraphBreak); + if !pending_text.is_empty() { + self.current_source = pending_source.take(); + if paragraph_break && self.can_reuse_plain_paragraph() { + let runs = paragraph_cache.parse(&pending_text); + if !runs.is_empty() { + self.push_block_at( + Block::Paragraph(runs), + self.current_source.clone(), + ); + } + } else { + self.append_text(&pending_text); + } + pending_text.clear(); + } + + self.current_source = Some(item.location.clone()); + let event = expanded::FrontendEvent { + position: item.position, + kind: kind.clone(), + location: item.location.clone(), + math_line_break_penalties: item.math_line_break_penalties, + }; + self.handle_frontend_event(&event); + item_index += 1; + if let expanded::FrontendEventKind::BeginEnvironment { + name: environment, .. + } = kind + { + item_index = + consume_environment_preamble(expanded, item_index, environment); + } + + if paragraph_break { + if rich_candidate + .as_ref() + .is_some_and(|candidate| candidate.end_index == item_index) + { + let candidate = rich_candidate + .take() + .expect("rich paragraph candidate was checked"); + if let Some(Block::Paragraph(runs)) = + self.document.blocks.get(candidate.block_index) + { + paragraph_cache.insert_rich(candidate.key, runs.clone()); + } + } + cache_scan_pending = true; + } else if pending_text.is_empty() && self.can_reuse_plain_paragraph() { + cache_scan_pending = true; + } + } + } + } + if !pending_text.is_empty() { + self.current_source = pending_source; + self.append_text(&pending_text); + } + self.finish_heading(); + self.flush_paragraph(); + if let Some(candidate) = rich_candidate + && candidate.end_index == expanded.items.len() + && let Some(Block::Paragraph(runs)) = self.document.blocks.get(candidate.block_index) + { + paragraph_cache.insert_rich(candidate.key, runs.clone()); + } + while !self.lists.is_empty() { + self.finish_list(); + } + self.finish_table(); + self.finish_bibliography(); + ParsedDocument(self.document) + } + + fn can_reuse_plain_paragraph(&self) -> bool { + self.paragraph.is_empty() + && self.heading.is_none() + && self.lists.is_empty() + && self.table.is_none() + && self.bibliography.is_none() + && !self.figure_active + && !self.table_active + && self.caption_capture.is_none() + && self.metadata_capture.is_none() + && self.framed_box.is_none() + && self.centered.is_none() + && self.inline_boxes.is_empty() + && !self.bold + && !self.italic + && !self.monospace + && self.text_style_stack.is_empty() + } + + fn finish_metadata(&mut self, field: expanded::MetadataField) { + let Some((active_field, runs)) = self.metadata_capture.take() else { + return; + }; + if active_field != field { + self.metadata_capture = Some((active_field, runs)); + return; + } + let value = runs.into_iter().map(|run| run.text).collect::(); + match field { + expanded::MetadataField::Title => self.document.title = value, + expanded::MetadataField::Author => self.document.author = value, + expanded::MetadataField::Date => self.document.date = value, + } + } + + fn begin_style(&mut self, style: expanded::TextStyle) { + self.text_style_stack.push(( + style, + self.bold, + self.italic, + self.monospace, + self.small_caps, + )); + match style { + expanded::TextStyle::Bold => self.bold = true, + expanded::TextStyle::Italic => self.italic = true, + expanded::TextStyle::Monospace => self.monospace = true, + expanded::TextStyle::SmallCaps => self.small_caps = true, + expanded::TextStyle::Normal => { + self.bold = false; + self.italic = false; + self.monospace = false; + self.small_caps = false; + } + } + } + + fn end_style(&mut self, style: expanded::TextStyle) { + if self + .text_style_stack + .last() + .is_some_and(|(active_style, _, _, _, _)| *active_style == style) + && let Some((_, bold, italic, monospace, small_caps)) = self.text_style_stack.pop() + { + self.bold = bold; + self.italic = italic; + self.monospace = monospace; + self.small_caps = small_caps; + } + } + + fn handle_frontend_event(&mut self, event: &expanded::FrontendEvent) { + self.current_source = Some(event.location.clone()); + match &event.kind { + expanded::FrontendEventKind::ParagraphBreak => self.paragraph_break(), + expanded::FrontendEventKind::PageBreak => { + self.flush_paragraph(); + self.push_block(Block::PageBreak); + } + expanded::FrontendEventKind::Kern(width) => self.append_kern(*width), + expanded::FrontendEventKind::Rule { + width, + raise, + height, + } => self.append_rule(*width, *raise, *height), + expanded::FrontendEventKind::HorizontalGlue(glue) => self.append_glue(*glue), + expanded::FrontendEventKind::VerticalGlue(glue) => self.append_vertical_glue(*glue), + expanded::FrontendEventKind::Penalty(penalty) => self.append_penalty(*penalty), + expanded::FrontendEventKind::MakeTitle => { + self.flush_paragraph(); + self.document.show_title = true; + } + expanded::FrontendEventKind::InlineBoxStart => { + self.inline_boxes.push(Vec::new()); + } + expanded::FrontendEventKind::InlineBoxEnd => { + if let Some(mut runs) = self.inline_boxes.pop() { + trim_run_end(&mut runs); + let run = Run { + text: String::new(), + math: None, + kern: None, + glue: None, + penalty: None, + rule: None, + box_run: Some(InlineBox { runs }), + unresolved_reference: None, + bold: false, + italic: false, + monospace: false, + }; + self.target_runs().push(run); + } + } + expanded::FrontendEventKind::FramedBoxStart => { + self.flush_paragraph(); + self.box_frame = true; + self.box_width = None; + if self.framed_box.is_none() { + self.framed_box = Some(Vec::new()); + } + } + expanded::FrontendEventKind::ParboxStart { width } => { + self.flush_paragraph(); + self.box_frame = false; + self.box_width = Some(*width); + if self.framed_box.is_none() { + self.framed_box = Some(Vec::new()); + } + } + expanded::FrontendEventKind::HorizontalRule { height, width } => { + self.flush_paragraph(); + self.push_block(Block::HorizontalRule { + height: *height, + width: *width, + }); + } + expanded::FrontendEventKind::FramedBoxEnd => { + if let Some(mut runs) = self.framed_box.take() { + trim_run_end(&mut runs); + let frame = self.box_frame; + let width = self.box_width.take(); + self.push_block(Block::FramedBox { runs, frame, width }); + } + } + expanded::FrontendEventKind::MetadataStart(field) => { + self.metadata_capture = Some((*field, Vec::new())); + } + expanded::FrontendEventKind::MetadataEnd(field) => { + self.finish_metadata(*field); + } + expanded::FrontendEventKind::Geometry(settings) => { + apply_geometry(&mut self.document, settings); + } + expanded::FrontendEventKind::TextStyleStart(style) => self.begin_style(*style), + expanded::FrontendEventKind::TextStyleEnd(style) => self.end_style(*style), + expanded::FrontendEventKind::TextStyleDeclare(style) => { + self.begin_style(*style); + self.style_declarations.push((self.group_depth, *style)); + } + expanded::FrontendEventKind::GroupStart => self.group_depth += 1, + expanded::FrontendEventKind::GroupEnd => { + let depth = self.group_depth; + while self + .style_declarations + .last() + .is_some_and(|(declaration_depth, _)| *declaration_depth >= depth) + { + if let Some((_, style)) = self.style_declarations.pop() { + self.end_style(style); + } + } + self.group_depth = self.group_depth.saturating_sub(1); + } + expanded::FrontendEventKind::LiteralAmpersand + | expanded::FrontendEventKind::MathCell => self.append_literal_ampersand(), + expanded::FrontendEventKind::LiteralCharacter(character) => { + self.append_text(&character.to_string()) + } + expanded::FrontendEventKind::LineBreak => self.append_text(" "), + expanded::FrontendEventKind::RowBreak => { + if self.table.is_some() { + self.finish_table_row(); + } else { + self.append_text(" "); + } + } + expanded::FrontendEventKind::ListItem => self.start_list_item(), + expanded::FrontendEventKind::TableCell => self.finish_table_cell(), + expanded::FrontendEventKind::TableRule => { + if let Some(table) = &mut self.table { + table.rules.push(table.rows.len()); + } + } + expanded::FrontendEventKind::DisplayMath { + expression, + environment, + rows, + } => { + self.flush_paragraph(); + let number_rows = matches!( + environment.as_deref(), + Some( + "equation" + | "align" + | "alignat" + | "flalign" + | "eqnarray" + | "gather" + | "multline" + ) + ); + let mut equation_numbers = Vec::with_capacity(rows.len()); + for row in rows { + let number = if let Some(tag) = &row.equation_tag { + Some(EquationNumber { + text: tag.text.clone(), + parenthesized: !tag.starred, + }) + } else if number_rows && !row.suppress_number { + self.equation_number += 1; + Some(EquationNumber { + text: self.equation_number.to_string(), + parenthesized: true, + }) + } else { + None + }; + let reference = number + .as_ref() + .map(|number| number.text.clone()) + .unwrap_or_else(|| "?".to_string()); + for key in &row.labels { + self.document.labels.insert(key.clone(), reference.clone()); + } + if number.is_some() { + self.current_reference = reference; + } + equation_numbers.push(number); + } + if equation_numbers.iter().all(Option::is_none) { + self.current_reference.clear(); + } + if !expression.plain_text().is_empty() { + self.push_block_at( + Block::Math { + expression: expression.clone(), + equation_numbers, + }, + Some(event.location.clone()), + ); + } + } + expanded::FrontendEventKind::InlineMath(expression) => { + self.append_math_expression(expression.clone()); + } + expanded::FrontendEventKind::MathSpace(_) => self.append_text(" "), + expanded::FrontendEventKind::DisplayMathStart + | expanded::FrontendEventKind::DisplayMathEnd(_) + | expanded::FrontendEventKind::SuppressEquationNumber + | expanded::FrontendEventKind::EquationTag(_) + | expanded::FrontendEventKind::InlineMathStart + | expanded::FrontendEventKind::InlineMathEnd(_) + | expanded::FrontendEventKind::MathFractionStart { .. } + | expanded::FrontendEventKind::MathFractionSeparator + | expanded::FrontendEventKind::MathFractionEnd + | expanded::FrontendEventKind::MathInfixFraction(..) + | expanded::FrontendEventKind::MathCharacter { .. } + | expanded::FrontendEventKind::MathUnicodeCharacter { .. } + | expanded::FrontendEventKind::MathUnicodeDelimiter { .. } + | expanded::FrontendEventKind::MathStyleChange(_) + | expanded::FrontendEventKind::MathChoiceStart + | expanded::FrontendEventKind::MathChoiceBranch(_) + | expanded::FrontendEventKind::MathChoiceEnd + | expanded::FrontendEventKind::MathLimitMode(_) + | expanded::FrontendEventKind::MathAccentStart { .. } + | expanded::FrontendEventKind::MathAccentEnd + | expanded::FrontendEventKind::MathFontStart(_) + | expanded::FrontendEventKind::MathFontEnd + | expanded::FrontendEventKind::MathPhantomStart(_) + | expanded::FrontendEventKind::MathPhantomEnd + | expanded::FrontendEventKind::MathOperatorStart + | expanded::FrontendEventKind::MathOperatorEnd + | expanded::FrontendEventKind::MathClassStart(_) + | expanded::FrontendEventKind::MathClassEnd + | expanded::FrontendEventKind::MathRootStart { .. } + | expanded::FrontendEventKind::MathRootSeparator + | expanded::FrontendEventKind::MathRootEnd + | expanded::FrontendEventKind::MathDelimiterStart { .. } + | expanded::FrontendEventKind::MathDelimiterMiddle { .. } + | expanded::FrontendEventKind::MathDelimiterEnd { .. } + | expanded::FrontendEventKind::MathManualDelimiter { .. } => {} + expanded::FrontendEventKind::EnvironmentArgument(argument) => { + if self.table.is_some() { + self.set_table_alignments(argument); + } + } + expanded::FrontendEventKind::BeginEnvironment { + name: environment, .. + } => self.handle_environment(true, environment), + expanded::FrontendEventKind::EndEnvironment { name, .. } => { + self.handle_environment(false, name) + } + expanded::FrontendEventKind::HeadingStart { level, numbered } => { + self.start_heading(*level, *numbered) + } + expanded::FrontendEventKind::HeadingEnd => self.finish_heading(), + expanded::FrontendEventKind::CaptionStart => { + self.flush_paragraph(); + self.caption_capture = Some(Vec::new()); + } + expanded::FrontendEventKind::CaptionEnd => { + if let Some(caption) = self.caption_capture.take() { + self.handle_caption(caption); + } + } + expanded::FrontendEventKind::Label(key) => { + let reference = if self.current_reference.is_empty() { + "?".to_string() + } else { + self.current_reference.clone() + }; + self.document.labels.insert(key.clone(), reference); + } + expanded::FrontendEventKind::Reference(key) => { + 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(), + )) + } + expanded::FrontendEventKind::BibliographyItem(key) => { + self.start_bibliography_item(key.clone()) + } + expanded::FrontendEventKind::IncludeGraphics { options, path } => { + self.add_image(path.clone(), options.clone()) + } + } + } + + fn append_math_expression(&mut self, expression: MathExpr) { + let text = expression.plain_text(); + if text.is_empty() { + return; + } + if self.paragraph.is_empty() + && self.heading.is_none() + && self.table.is_none() + && self.lists.is_empty() + { + self.paragraph_source = self.current_source.clone(); + } + let bold = self.bold; + self.target_runs().push(Run { + text, + math: Some(expression), + kern: None, + glue: None, + penalty: None, + rule: None, + box_run: None, + unresolved_reference: None, + bold, + italic: true, + monospace: false, + }); + } + + fn start_heading(&mut self, level: u8, numbered: bool) { + self.flush_paragraph(); + self.finish_heading(); + let level = level.clamp(1, 3); + let runs = if numbered { + let number = self.next_section_number(level); + self.current_reference = number.clone(); + vec![Run::plain(format!("{number} "))] + } else { + self.current_reference.clear(); + Vec::new() + }; + self.heading = Some(HeadingBuilder { + level, + runs, + source: self.current_source.clone(), + }); + } + + fn finish_heading(&mut self) { + if let Some(mut heading) = self.heading.take() { + trim_run_end(&mut heading.runs); + self.push_block_at( + Block::Heading { + level: heading.level, + runs: heading.runs, + }, + heading.source, + ); + } + } + + fn append_text(&mut self, text: &str) { + if !text.is_empty() + && self.paragraph.is_empty() + && self.heading.is_none() + && self.table.is_none() + && self.lists.is_empty() + && self.metadata_capture.is_none() + { + self.paragraph_source = self.current_source.clone(); + } + let uppercased; + let text: &str = if self.small_caps { + uppercased = text.to_uppercase(); + uppercased.as_str() + } else { + text + }; + let bold = self.bold; + let italic = self.italic; + let monospace = self.monospace; + if self.table.is_some() { + let mut pieces = text.split('&').peekable(); + while let Some(piece) = pieces.next() { + append_run( + self.target_runs(), + normalize_whitespace(piece), + bold, + italic, + monospace, + ); + if pieces.peek().is_some() { + self.finish_table_cell(); + } + } + } else { + append_run( + self.target_runs(), + normalize_whitespace(text), + bold, + italic, + monospace, + ); + } + } + + fn append_kern(&mut self, width: common::Scaled) { + let in_vertical_mode = self.paragraph.is_empty() + && self.heading.is_none() + && self.lists.is_empty() + && self.table.is_none() + && self.bibliography.is_none() + && self.caption_capture.is_none() + && self.metadata_capture.is_none() + && self.framed_box.is_none() + && self.centered.is_none() + && self.inline_boxes.is_empty() + && !self.figure_active; + if in_vertical_mode { + self.push_block(Block::VerticalKern(width)); + return; + } + + let bold = self.bold; + let italic = self.italic; + let monospace = self.monospace; + self.target_runs().push(Run { + text: String::new(), + math: None, + kern: Some(width), + glue: None, + penalty: None, + rule: None, + box_run: None, + unresolved_reference: None, + bold, + italic, + monospace, + }); + } + + fn append_rule( + &mut self, + width: common::Scaled, + raise: common::Scaled, + height: common::Scaled, + ) { + let bold = self.bold; + let italic = self.italic; + let monospace = self.monospace; + self.target_runs().push(Run { + text: String::new(), + math: None, + kern: None, + glue: None, + penalty: None, + rule: Some(RuleBox { + width, + raise, + height, + }), + box_run: None, + unresolved_reference: None, + bold, + italic, + monospace, + }); + } + + fn append_glue(&mut self, glue: TeXGlue) { + if self.paragraph.is_empty() + && self.heading.is_none() + && self.lists.is_empty() + && self.table.is_none() + && self.bibliography.is_none() + && self.caption_capture.is_none() + && self.metadata_capture.is_none() + && self.framed_box.is_none() + && self.centered.is_none() + && self.inline_boxes.is_empty() + { + self.paragraph_source = self.current_source.clone(); + } + + let bold = self.bold; + let italic = self.italic; + let monospace = self.monospace; + self.target_runs().push(Run { + text: String::new(), + math: None, + kern: None, + glue: Some(glue), + penalty: None, + rule: None, + box_run: None, + unresolved_reference: None, + bold, + italic, + monospace, + }); + } + + fn append_vertical_glue(&mut self, glue: TeXGlue) { + if let Some(list) = self.lists.last_mut() { + list.vertical_glue_after.push(glue); + return; + } + self.flush_paragraph(); + self.push_block(Block::VerticalGlue(glue)); + } + + fn append_penalty(&mut self, penalty: i32) { + let in_vertical_mode = self.paragraph.is_empty() + && self.heading.is_none() + && self.lists.is_empty() + && self.table.is_none() + && self.bibliography.is_none() + && self.caption_capture.is_none() + && self.metadata_capture.is_none() + && self.framed_box.is_none() + && self.centered.is_none() + && self.inline_boxes.is_empty(); + if in_vertical_mode { + self.push_block(Block::Penalty(penalty)); + return; + } + + let bold = self.bold; + let italic = self.italic; + let monospace = self.monospace; + self.target_runs().push(Run { + text: String::new(), + math: None, + kern: None, + glue: None, + penalty: Some(penalty), + rule: None, + box_run: None, + unresolved_reference: None, + bold, + italic, + monospace, + }); + } + + fn target_runs(&mut self) -> &mut Vec { + if let Some(runs) = self.inline_boxes.last_mut() { + runs + } else if let Some(runs) = &mut self.centered { + runs + } else if let Some(runs) = &mut self.framed_box { + runs + } else if let Some((_, metadata)) = &mut self.metadata_capture { + metadata + } else if let Some(caption) = &mut self.caption_capture { + caption + } else if let Some(heading) = &mut self.heading { + &mut heading.runs + } else if let Some(table) = &mut self.table { + &mut table.cell + } else if let Some(bibliography) = &mut self.bibliography { + if let Some((_, runs)) = &mut bibliography.current { + runs + } else { + &mut self.paragraph + } + } else if let Some(list) = self.lists.last_mut() { + &mut list.current + } else { + &mut self.paragraph + } + } + + fn append_literal_ampersand(&mut self) { + let bold = self.bold; + let italic = self.italic; + let monospace = self.monospace; + append_run(self.target_runs(), "&".to_string(), bold, italic, monospace); + } + + fn append_reference(&mut self, reference: UnresolvedReference) { + if self.paragraph.is_empty() + && self.heading.is_none() + && self.table.is_none() + && self.lists.is_empty() + && self.bibliography.is_none() + && self.caption_capture.is_none() + && self.metadata_capture.is_none() + && self.framed_box.is_none() + && self.centered.is_none() + && self.inline_boxes.is_empty() + { + self.paragraph_source = self.current_source.clone(); + } + let bold = self.bold; + let italic = self.italic; + let monospace = self.monospace; + self.target_runs().push(Run { + text: String::new(), + math: None, + kern: None, + glue: None, + penalty: None, + rule: None, + box_run: None, + unresolved_reference: Some(reference), + bold, + italic, + monospace, + }); + } + + fn paragraph_break(&mut self) { + if !self.lists.is_empty() || self.table.is_some() { + self.append_text(" "); + } else { + self.flush_paragraph(); + } + } + + fn flush_paragraph(&mut self) { + trim_run_end(&mut self.paragraph); + if !self.paragraph.is_empty() { + let runs = std::mem::take(&mut self.paragraph); + let source = self.paragraph_source.take(); + self.push_block_at(Block::Paragraph(runs), source); + } else { + self.paragraph_source = None; + } + } + + fn push_block(&mut self, block: Block) { + self.push_block_at(block, self.current_source.clone()); + } + + fn push_block_at(&mut self, block: Block, source: Option) { + self.document.blocks.push(block); + self.document.block_sources.push(source); + } + + fn start_list_item(&mut self) { + if self.lists.is_empty() { + self.flush_paragraph(); + self.lists.push(ListBuilder::default()); + } + if let Some(list) = self.lists.last_mut() { + list.finish_current_item(); + list.has_current_item = true; + } + } + + fn handle_environment(&mut self, begin: bool, environment: &str) { + match (begin, environment) { + (true, "itemize") | (true, "enumerate") => { + self.flush_paragraph(); + if let Some(parent) = self.lists.last_mut() { + parent.has_current_item = true; + } + self.lists.push(ListBuilder { + ordered: environment == "enumerate", + ..ListBuilder::default() + }); + } + (false, "itemize") | (false, "enumerate") => { + self.flush_paragraph(); + self.finish_list(); + } + (true, "tabular") => { + self.flush_paragraph(); + self.finish_list(); + self.table = Some(TableBuilder { + caption: self.pending_table_caption.take(), + ..TableBuilder::default() + }); + if !self.table_active { + self.table_number += 1; + self.current_reference = self.table_number.to_string(); + } + } + (false, "tabular") => self.finish_table(), + (true, "figure") => { + self.flush_paragraph(); + self.figure_active = true; + self.figure_image = None; + self.figure_number += 1; + self.current_reference = self.figure_number.to_string(); + } + (false, "figure") => { + self.flush_paragraph(); + self.figure_active = false; + self.figure_image = None; + } + (true, "table") => { + self.flush_paragraph(); + self.table_active = true; + self.current_table_block = None; + self.pending_table_caption = None; + self.table_number += 1; + self.current_reference = self.table_number.to_string(); + } + (false, "table") => { + self.flush_paragraph(); + self.table_active = false; + self.current_table_block = None; + } + (true, "center") => { + self.flush_paragraph(); + if self.centered.is_none() { + self.centered = Some(Vec::new()); + } + } + (false, "center") => { + if let Some(mut runs) = self.centered.take() { + trim_run_end(&mut runs); + self.push_block(Block::Centered { runs }); + } + } + (true, "thebibliography") => { + self.flush_paragraph(); + self.bibliography = Some(BibliographyBuilder::default()); + } + (false, "thebibliography") => self.finish_bibliography(), + _ => {} + } + } + + fn next_section_number(&mut self, level: u8) -> String { + let index = usize::from(level.saturating_sub(1).min(2)); + self.section_numbers[index] += 1; + self.section_numbers[index + 1..].fill(0); + self.section_numbers[..=index] + .iter() + .map(u32::to_string) + .collect::>() + .join(".") + } + + fn add_image(&mut self, path: String, options: String) { + if self.metadata_capture.is_some() { + // Title metadata is stored as plain text, so inline images (such as + // ORCID icons inside \author) are dropped here. + return; + } + self.flush_paragraph(); + if !self.figure_active { + self.figure_number += 1; + } + self.current_reference = self.figure_number.to_string(); + let index = self.document.blocks.len(); + self.push_block(Block::Image { + path, + options, + caption: None, + }); + if self.figure_active { + self.figure_image = Some(index); + } + } + + fn handle_caption(&mut self, caption: Vec) { + self.flush_paragraph(); + if self.figure_active { + self.current_reference = self.figure_number.to_string(); + let caption = caption_with_prefix(format!("Figure {}: ", self.figure_number), caption); + if let Some(index) = self.figure_image + && let Some(Block::Image { + caption: image_caption, + .. + }) = self.document.blocks.get_mut(index) + { + *image_caption = Some(caption); + return; + } + self.push_block(Block::Paragraph(caption)); + return; + } + if let Some(table) = &mut self.table { + self.current_reference = self.table_number.to_string(); + table.caption = Some(caption_with_prefix( + format!("Table {}: ", self.table_number), + caption, + )); + return; + } + if self.table_active { + self.current_reference = self.table_number.to_string(); + let caption = caption_with_prefix(format!("Table {}: ", self.table_number), caption); + if let Some(index) = self.current_table_block + && let Some(Block::Table { + caption: table_caption, + .. + }) = self.document.blocks.get_mut(index) + { + *table_caption = Some(caption); + } else { + self.pending_table_caption = Some(caption); + } + } else { + self.push_block(Block::Paragraph(caption)); + } + } + + fn finish_table_cell(&mut self) { + if let Some(table) = &mut self.table { + trim_run_end(&mut table.cell); + table.row.push(std::mem::take(&mut table.cell)); + } + } + + fn finish_table_row(&mut self) { + self.finish_table_cell(); + if let Some(table) = &mut self.table + && !table.row.is_empty() + { + table.rows.push(std::mem::take(&mut table.row)); + } + } + + fn finish_table(&mut self) { + self.finish_table_row(); + if let Some(table) = self.table.take() + && !table.rows.is_empty() + { + let index = self.document.blocks.len(); + let caption = table.caption.or_else(|| self.pending_table_caption.take()); + self.push_block(Block::Table { + rows: table.rows, + caption, + alignments: table.alignments, + rules: table.rules, + }); + if self.table_active { + self.current_table_block = Some(index); + } + } + } + + fn start_bibliography_item(&mut self, key: String) { + self.flush_paragraph(); + self.finish_bibliography_item(); + if let Some(bibliography) = &mut self.bibliography { + let number = bibliography.items.len() + 1; + self.document.citations.insert(key.clone(), number); + self.current_reference = number.to_string(); + bibliography.current = Some((key, Vec::new())); + } + } + + fn finish_bibliography_item(&mut self) { + if let Some(bibliography) = &mut self.bibliography + && let Some((key, mut runs)) = bibliography.current.take() + { + trim_run_end(&mut runs); + bibliography.items.push((key, runs)); + } + } + + fn finish_bibliography(&mut self) { + self.finish_bibliography_item(); + if let Some(bibliography) = self.bibliography.take() + && !bibliography.items.is_empty() + { + self.push_block(Block::Bibliography(bibliography.items)); + } + } + + fn finish_list(&mut self) { + if let Some(mut list) = self.lists.pop() { + list.finish_current_item(); + if !list.items.is_empty() { + let block = ListBlock { + ordered: list.ordered, + items: list.items, + }; + if let Some(parent) = self.lists.last_mut() { + parent.has_current_item = true; + parent.nested.push(block); + } else { + self.push_block(Block::List(block)); + } + } + } + } + + fn set_table_alignments(&mut self, specification: &str) { + let Some(table) = &mut self.table else { + return; + }; + let mut chars = specification.chars().peekable(); + while let Some(character) = chars.next() { + match character { + 'l' => table.alignments.push(ColumnAlignment::Left), + 'c' => table.alignments.push(ColumnAlignment::Center), + 'r' => table.alignments.push(ColumnAlignment::Right), + 'p' | 'm' | 'b' => { + if chars.peek() == Some(&'{') { + chars.next(); + for nested in chars.by_ref() { + if nested == '}' { + break; + } + } + } + table.alignments.push(ColumnAlignment::Left); + } + _ => {} + } + } + } +} + +pub fn parse_document( + source: &expanded::ExpandedTokenStream, + paragraph_cache: &mut ParagraphParseCache, +) -> ParsedDocument { + Parser::new().parse(source, paragraph_cache) +} + +fn append_run(runs: &mut Vec, mut text: String, bold: bool, italic: bool, monospace: bool) { + if text.is_empty() { + return; + } + if runs.is_empty() || runs.last().is_some_and(|run| run.text.ends_with(' ')) { + text = text.trim_start().to_string(); + } + if text.is_empty() { + return; + } + if let Some(last) = runs.last_mut() + && last.math.is_none() + && last.kern.is_none() + && last.glue.is_none() + && last.penalty.is_none() + && last.rule.is_none() + && last.box_run.is_none() + && last.unresolved_reference.is_none() + && last.bold == bold + && last.italic == italic + && last.monospace == monospace + { + last.text.push_str(&text); + return; + } + runs.push(Run { + text, + math: None, + kern: None, + glue: None, + penalty: None, + rule: None, + box_run: None, + unresolved_reference: None, + bold, + italic, + monospace, + }); +} + +fn trim_run_end(runs: &mut Vec) { + if let Some(last) = runs.last_mut() { + last.text = last.text.trim_end().to_string(); + if last.text.is_empty() + && last.kern.is_none() + && last.glue.is_none() + && last.penalty.is_none() + && last.rule.is_none() + && last.box_run.is_none() + && last.unresolved_reference.is_none() + { + runs.pop(); + } + } +} + +fn normalize_whitespace(text: &str) -> String { + let mut output = String::with_capacity(text.len()); + let mut previous_whitespace = false; + for character in text.chars() { + if character.is_whitespace() { + if !previous_whitespace { + output.push(' '); + } + previous_whitespace = true; + } else { + output.push(character); + previous_whitespace = false; + } + } + output +} + +fn apply_geometry(document: &mut DocumentModel, settings: &str) { + let page = &mut document.page; + // Paper size first: explicit margins in the same list must be measured + // against the final page dimensions. + for setting in settings.split(',') { + let setting = setting.trim(); + if setting.is_empty() { + continue; + } + let (key, value) = match setting.split_once('=') { + Some((key, value)) => (key.trim(), Some(value.trim())), + None => (setting, None), + }; + match key { + "a4paper" => *page = PageSize::A4, + "a5paper" => *page = PageSize::A5, + "b5paper" => *page = PageSize::B5, + "letterpaper" => *page = PageSize::LETTER, + "legalpaper" => *page = PageSize::LEGAL, + "executivepaper" => *page = PageSize::EXECUTIVE, + "landscape" => *page = page.landscape(), + "paperwidth" => { + if let Some(value) = value.and_then(parse_dimension) { + page.width_mm = value; + } + } + "paperheight" => { + if let Some(value) = value.and_then(parse_dimension) { + page.height_mm = value; + } + } + _ => {} + } + } + + let margins = &mut document.margins; + for setting in settings.split(',') { + let Some((key, value)) = setting.split_once('=') else { + continue; + }; + let Some(value) = parse_dimension(value.trim()) else { + continue; + }; + match key.trim() { + "margin" => { + *margins = PageMargins { + top: value, + right: value, + bottom: value, + left: value, + }; + } + "top" | "tmargin" => margins.top = value, + "right" | "rmargin" => margins.right = value, + "bottom" | "bmargin" => margins.bottom = value, + "left" | "lmargin" => margins.left = value, + "hmargin" => { + margins.left = value; + margins.right = value; + } + "vmargin" => { + margins.top = value; + margins.bottom = value; + } + _ => {} + } + } + + // Text-block dimensions are resolved after explicit margins so that top + // influences the computed bottom margin in the same settings list. + let page_width = document.page.width_mm; + let page_height = document.page.height_mm; + let margins = &mut document.margins; + for setting in settings.split(',') { + let Some((key, value)) = setting.split_once('=') else { + continue; + }; + let Some(value) = parse_dimension(value.trim()) else { + continue; + }; + match key.trim() { + "textwidth" => { + let side = ((page_width - value) / 2.0).max(0.0); + margins.left = side; + margins.right = side; + } + "textheight" => { + margins.bottom = (page_height - margins.top - value).max(0.0); + } + _ => {} + } + } +} + +pub fn parse_dimension(value: &str) -> Option { + let split = value + .find(|character: char| { + !(character.is_ascii_digit() || character == '.' || character == '-') + }) + .unwrap_or(value.len()); + let number = value[..split].parse::().ok()?; + let multiplier = match value[split..].trim() { + "mm" => 1.0, + "cm" => 10.0, + "in" => 25.4, + "pt" => 25.4 / 72.27, + "bp" => 25.4 / 72.0, + "" => return None, + _ => return None, + }; + (number.is_finite() && number > 0.0).then_some(number * multiplier) +} + +fn caption_with_prefix(prefix: String, caption: Vec) -> Vec { + let mut runs = Vec::with_capacity(caption.len() + 1); + runs.push(Run::plain(prefix)); + runs.extend(caption); + runs +} diff --git a/crates/texrra-core/src/environment.rs b/crates/texrra-core/src/environment.rs new file mode 100644 index 0000000..106b1f4 --- /dev/null +++ b/crates/texrra-core/src/environment.rs @@ -0,0 +1,63 @@ +use std::fmt; + +#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] +pub struct EnvironmentStack { + names: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EndEnvironmentError { + Unmatched { requested: String }, + Mismatched { active: String, requested: String }, +} + +impl fmt::Display for EndEnvironmentError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Unmatched { requested } => { + write!( + formatter, + "`\\end{{{requested}}}` has no matching `\\begin`" + ) + } + Self::Mismatched { active, requested } => write!( + formatter, + "environment `{active}` was ended by `\\end{{{requested}}}`" + ), + } + } +} + +impl EnvironmentStack { + pub fn begin(&mut self, name: String) { + self.names.push(name); + } + + pub fn opens_tex_group(name: &str) -> bool { + name != "document" + } + + pub fn current(&self) -> Option<&str> { + self.names.last().map(String::as_str) + } + + pub fn end(&mut self, requested: &str) -> Result<(), EndEnvironmentError> { + match self.current() { + Some(active) if active == requested => { + self.names.pop(); + Ok(()) + } + Some(active) => Err(EndEnvironmentError::Mismatched { + active: active.to_string(), + requested: requested.to_string(), + }), + None => Err(EndEnvironmentError::Unmatched { + requested: requested.to_string(), + }), + } + } + + pub fn as_slice(&self) -> &[String] { + &self.names + } +} diff --git a/crates/texrra-core/src/expanded.rs b/crates/texrra-core/src/expanded.rs new file mode 100644 index 0000000..2e46e13 --- /dev/null +++ b/crates/texrra-core/src/expanded.rs @@ -0,0 +1,617 @@ +use std::{ops::Range, sync::Arc}; + +use crate::{ + MathClass, MathStyleCommand, TeXGlue, + math_code::UnicodeMathCode, + math_expr::{ + MathAccent, MathDelimiterGlyph, MathDelimiterSettings, MathExpr, MathFontFamilies, + MathFontStyle, MathFractionStyle, MathInfixFractionKind, MathLimitMode, + MathLineBreakPenalties, MathPhantomKind, MathSpacingSettings, + }, + source::SourceLocation, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum TextStyle { + Bold, + Italic, + Monospace, + SmallCaps, + Normal, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MetadataField { + Title, + Author, + Date, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct SourceSegment { + pub output: Range, + pub location: SourceLocation, + pub column_advances: bool, + pub column_character_starts: Vec, +} + +fn rebased_column_character_starts( + segment: &SourceSegment, + start: usize, + end: usize, +) -> Vec { + let start_offset = start - segment.output.start; + let end_offset = end - segment.output.start; + segment + .column_character_starts + .iter() + .filter_map(|offset| { + (*offset >= start_offset && *offset < end_offset).then_some(*offset - start_offset) + }) + .collect() +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct DisplayMathTag { + pub text: String, + pub starred: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct DisplayMathRow { + pub equation_tag: Option, + pub suppress_number: bool, + pub labels: Vec, +} + +impl Default for DisplayMathRow { + fn default() -> Self { + Self { + equation_tag: None, + suppress_number: false, + labels: Vec::new(), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum FrontendEventKind { + ParagraphBreak, + PageBreak, + Kern(common::Scaled), + Rule { + width: common::Scaled, + raise: common::Scaled, + height: common::Scaled, + }, + HorizontalGlue(TeXGlue), + VerticalGlue(TeXGlue), + Penalty(i32), + MakeTitle, + FramedBoxStart, + ParboxStart { + width: common::Scaled, + }, + HorizontalRule { + height: common::Scaled, + width: Option, + }, + FramedBoxEnd, + InlineBoxStart, + InlineBoxEnd, + MetadataStart(MetadataField), + MetadataEnd(MetadataField), + DisplayMathStart, + DisplayMathEnd(MathDelimiterSettings), + InlineMathStart, + InlineMathEnd(MathDelimiterSettings), + DisplayMath { + expression: MathExpr, + environment: Option, + rows: Vec, + }, + SuppressEquationNumber, + EquationTag(DisplayMathTag), + InlineMath(MathExpr), + MathFractionStart { + style: MathFractionStyle, + has_rule: bool, + parentheses: bool, + delimiter_settings: MathDelimiterSettings, + math_fonts: MathFontFamilies, + }, + MathInfixFraction(MathInfixFractionKind, MathFontFamilies), + MathCharacter { + code: u16, + active_family: i32, + math_fonts: MathFontFamilies, + }, + MathUnicodeCharacter { + class: MathClass, + family: u8, + character: char, + math_fonts: MathFontFamilies, + }, + MathUnicodeDelimiter { + class: MathClass, + family: u8, + character: char, + settings: MathDelimiterSettings, + math_fonts: MathFontFamilies, + }, + MathStyleChange(MathStyleCommand), + MathChoiceStart, + MathChoiceBranch(MathStyleCommand), + MathChoiceEnd, + MathFractionSeparator, + MathFractionEnd, + MathLimitMode(MathLimitMode), + MathSpace(i8), + MathAccentStart { + accent: MathAccent, + family: u8, + math_fonts: MathFontFamilies, + }, + MathAccentEnd, + MathFontStart(MathFontStyle), + MathFontEnd, + MathPhantomStart(MathPhantomKind), + MathPhantomEnd, + MathOperatorStart, + MathOperatorEnd, + MathClassStart(MathClass), + MathClassEnd, + MathRootStart { + has_index: bool, + radical: Option<(u8, char)>, + math_fonts: MathFontFamilies, + }, + MathRootSeparator, + MathRootEnd, + MathDelimiterStart { + delimiter: MathDelimiterGlyph, + settings: MathDelimiterSettings, + }, + MathDelimiterMiddle { + delimiter: MathDelimiterGlyph, + settings: MathDelimiterSettings, + }, + MathDelimiterEnd { + delimiter: MathDelimiterGlyph, + settings: MathDelimiterSettings, + }, + MathManualDelimiter { + delimiter: String, + half_points: u8, + class: MathClass, + settings: MathDelimiterSettings, + math_fonts: MathFontFamilies, + }, + BeginEnvironment { + name: String, + math_fonts: MathFontFamilies, + jot: common::Scaled, + }, + EnvironmentArgument(String), + EndEnvironment { + name: String, + delimiter_settings: MathDelimiterSettings, + }, + Geometry(String), + TextStyleStart(TextStyle), + TextStyleEnd(TextStyle), + TextStyleDeclare(TextStyle), + LiteralAmpersand, + LiteralCharacter(char), + LineBreak, + MathCell, + RowBreak, + ListItem, + TableCell, + TableRule, + HeadingStart { + level: u8, + numbered: bool, + }, + HeadingEnd, + CaptionStart, + CaptionEnd, + IncludeGraphics { + options: String, + path: String, + }, + Label(String), + Reference(String), + Citation(String), + BibliographyItem(String), + GroupStart, + GroupEnd, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct FrontendEvent { + pub position: usize, + pub kind: FrontendEventKind, + pub location: SourceLocation, + pub math_line_break_penalties: MathLineBreakPenalties, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum ExpandedTokenValue { + BeginGroup(char), + EndGroup(char), + MathShift(char), + AlignmentTab(char), + Parameter(char), + Superscript(char), + Subscript(char), + Space(char), + Letter(char), + Other(char), + ActiveCharacter(char), + ControlSequence(String), +} + +impl ExpandedTokenValue { + pub fn character(&self) -> Option { + match self { + Self::BeginGroup(character) + | Self::EndGroup(character) + | Self::MathShift(character) + | Self::AlignmentTab(character) + | Self::Parameter(character) + | Self::Superscript(character) + | Self::Subscript(character) + | Self::Space(character) + | Self::Letter(character) + | Self::Other(character) + | Self::ActiveCharacter(character) => Some(*character), + Self::ControlSequence(_) => None, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum ExpandedItemKind { + Token(ExpandedTokenValue), + Event(FrontendEventKind), +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct ExpandedItem { + pub position: usize, + pub end_position: usize, + pub kind: ExpandedItemKind, + pub location: SourceLocation, + pub math_code: Option, + pub math_family: Option, + pub unicode_math_code: Option, + pub delimiter_settings: Option, + pub math_fonts: MathFontFamilies, + pub math_spacing: MathSpacingSettings, + pub math_line_break_penalties: MathLineBreakPenalties, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ExpandedSource { + pub text: String, + pub segments: Vec, + pub events: Vec, + pub items: Vec, +} + +/// Semantic consumers receive typed items without the VM's serialized text view. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ExpandedTokenStream { + pub items: Vec, + pub segments: Vec, + pub events: Vec, +} + +impl ExpandedSource { + pub fn into_token_stream(self) -> ExpandedTokenStream { + ExpandedTokenStream { + items: self.items, + segments: self.segments, + events: self.events, + } + } + + pub fn source_at(&self, output_offset: usize) -> Option { + let index = self + .segments + .partition_point(|segment| segment.output.end <= output_offset); + let segment = self + .segments + .get(index) + .filter(|segment| segment.output.contains(&output_offset))?; + Some(self.location_at(segment, output_offset)) + } + + fn location_at(&self, segment: &SourceSegment, output_offset: usize) -> SourceLocation { + let mut location = segment.location.clone(); + if segment.column_advances { + let byte_offset = output_offset - segment.output.start; + location.column += segment + .column_character_starts + .partition_point(|start| *start < byte_offset); + } + location + } +} + +impl ExpandedTokenStream { + pub fn output_len(&self) -> usize { + self.items + .last() + .map(|item| item.end_position) + .unwrap_or_default() + .max( + self.segments + .last() + .map(|segment| segment.output.end) + .unwrap_or_default(), + ) + .max( + self.events + .last() + .map(|event| event.position) + .unwrap_or_default(), + ) + } + + pub fn token_item_at(&self, output_offset: usize) -> Option<&ExpandedItem> { + let item_start = self + .items + .partition_point(|item| item.position < output_offset); + self.items[item_start..] + .iter() + .take_while(|item| item.position == output_offset) + .find(|item| { + item.end_position > item.position + && matches!(&item.kind, ExpandedItemKind::Token(_)) + }) + } + + pub fn next_token_item_at_or_after( + &self, + output_offset: usize, + limit: usize, + ) -> Option<&ExpandedItem> { + let item_start = self + .items + .partition_point(|item| item.position < output_offset); + self.items[item_start..] + .iter() + .take_while(|item| item.position < limit) + .find(|item| { + item.end_position > item.position + && matches!(&item.kind, ExpandedItemKind::Token(_)) + }) + } + + pub fn token_value_at(&self, output_offset: usize) -> Option<&ExpandedTokenValue> { + let item = self.token_item_at(output_offset)?; + match &item.kind { + ExpandedItemKind::Token(value) => Some(value), + ExpandedItemKind::Event(_) => unreachable!(), + } + } + + pub fn character_tokens_in(&self, range: Range) -> String { + let item_start = self + .items + .partition_point(|item| item.position < range.start); + let mut text = String::new(); + for item in self.items[item_start..] + .iter() + .take_while(|item| item.position < range.end) + { + let ExpandedItemKind::Token(value) = &item.kind else { + continue; + }; + if let Some(character) = value.character() { + text.push(character); + } + } + text + } + + pub fn source_at(&self, output_offset: usize) -> Option { + let index = self + .segments + .partition_point(|segment| segment.output.end <= output_offset); + let segment = self + .segments + .get(index) + .filter(|segment| segment.output.contains(&output_offset))?; + Some(self.location_at(segment, output_offset)) + } + + fn location_at(&self, segment: &SourceSegment, output_offset: usize) -> SourceLocation { + let mut location = segment.location.clone(); + if segment.column_advances { + let byte_offset = output_offset - segment.output.start; + location.column += segment + .column_character_starts + .partition_point(|start| *start < byte_offset); + } + location + } + + pub fn segment_signature(&self, range: Range) -> Vec { + self.segments + .iter() + .filter_map(|segment| { + let start = segment.output.start.max(range.start); + let end = segment.output.end.min(range.end); + (start < end).then(|| SourceSegment { + output: start - range.start..end - range.start, + location: self.location_at(segment, start), + column_advances: segment.column_advances, + column_character_starts: rebased_column_character_starts(segment, start, end), + }) + }) + .collect() + } + + pub fn copy_token_range(&mut self, source: &Self, range: Range) { + if range.is_empty() { + return; + } + let destination_start = self.output_len(); + self.copy_segments(source, &range, destination_start); + self.items.extend(source.items.iter().filter_map(|item| { + (range.start <= item.position + && item.position < range.end + && matches!(&item.kind, ExpandedItemKind::Token(_))) + .then(|| rebase_expanded_item(item, destination_start, range.start)) + })); + } + + /// Copies a slice of source items onto the current output in item order. + /// + /// Items with zero output width (space tokens and events) share their byte + /// position with the next written token; copying by item index keeps those + /// items in expansion order instead of splitting them by position. + pub fn copy_items(&mut self, source: &Self, items: &[ExpandedItem]) { + if items.is_empty() { + return; + } + let destination_start = self.output_len(); + let position_start = items[0].position; + let position_end = items + .iter() + .map(|item| item.end_position.max(item.position)) + .max() + .unwrap_or(position_start); + if position_end > position_start { + self.copy_segments(source, &(position_start..position_end), destination_start); + } + for item in items { + let item = rebase_expanded_item(item, destination_start, position_start); + if let ExpandedItemKind::Event(kind) = &item.kind { + self.events.push(FrontendEvent { + position: item.position, + kind: kind.clone(), + location: item.location.clone(), + math_line_break_penalties: item.math_line_break_penalties, + }); + } + self.items.push(item); + } + } + + pub fn copy_range(&mut self, source: &Self, range: Range) { + if range.is_empty() { + return; + } + let destination_start = self.output_len(); + self.copy_segments(source, &range, destination_start); + for item in source + .items + .iter() + .filter(|item| range.start <= item.position && item.position < range.end) + { + let item = rebase_expanded_item(item, destination_start, range.start); + if let ExpandedItemKind::Event(kind) = &item.kind { + self.events.push(FrontendEvent { + position: item.position, + kind: kind.clone(), + location: item.location.clone(), + math_line_break_penalties: item.math_line_break_penalties, + }); + } + self.items.push(item); + } + } + + fn copy_segments(&mut self, source: &Self, range: &Range, destination_start: usize) { + for segment in &source.segments { + let start = segment.output.start.max(range.start); + let end = segment.output.end.min(range.end); + if start < end { + self.segments.push(SourceSegment { + output: destination_start + start - range.start + ..destination_start + end - range.start, + location: source.location_at(segment, start), + column_advances: segment.column_advances, + column_character_starts: rebased_column_character_starts(segment, start, end), + }); + } + } + } + + pub fn copy_events_at(&mut self, source: &Self, source_position: usize) { + let destination_position = self.output_len(); + for item in source.items.iter().filter(|item| { + item.position == source_position && matches!(&item.kind, ExpandedItemKind::Event(_)) + }) { + let ExpandedItemKind::Event(kind) = &item.kind else { + unreachable!(); + }; + self.events.push(FrontendEvent { + position: destination_position, + kind: kind.clone(), + location: item.location.clone(), + math_line_break_penalties: item.math_line_break_penalties, + }); + self.items.push(ExpandedItem { + position: destination_position, + end_position: destination_position, + kind: item.kind.clone(), + location: item.location.clone(), + math_code: None, + math_family: None, + unicode_math_code: None, + delimiter_settings: None, + math_fonts: Arc::default(), + math_spacing: MathSpacingSettings::default(), + math_line_break_penalties: item.math_line_break_penalties, + }); + } + } + + pub fn insert_event(&mut self, kind: FrontendEventKind, location: SourceLocation) { + let position = self.output_len(); + self.events.push(FrontendEvent { + position, + kind: kind.clone(), + location: location.clone(), + math_line_break_penalties: MathLineBreakPenalties::default(), + }); + self.items.push(ExpandedItem { + position, + end_position: position, + kind: ExpandedItemKind::Event(kind), + location, + math_code: None, + math_family: None, + unicode_math_code: None, + delimiter_settings: None, + math_fonts: Arc::default(), + math_spacing: MathSpacingSettings::default(), + math_line_break_penalties: MathLineBreakPenalties::default(), + }); + } +} + +fn rebase_expanded_item( + item: &ExpandedItem, + destination_start: usize, + source_start: usize, +) -> ExpandedItem { + ExpandedItem { + position: destination_start + item.position - source_start, + end_position: destination_start + item.end_position - source_start, + kind: item.kind.clone(), + location: item.location.clone(), + math_code: item.math_code, + math_family: item.math_family, + unicode_math_code: item.unicode_math_code, + delimiter_settings: item.delimiter_settings, + math_fonts: Arc::clone(&item.math_fonts), + math_spacing: item.math_spacing, + math_line_break_penalties: item.math_line_break_penalties, + } +} diff --git a/crates/texrra-core/src/expansion.rs b/crates/texrra-core/src/expansion.rs new file mode 100644 index 0000000..bea762e --- /dev/null +++ b/crates/texrra-core/src/expansion.rs @@ -0,0 +1,470 @@ +use crate::{CatCode as EngineCatCode, EngineToken, EngineTokenValue, macros::MacroDefinition}; + +pub trait MacroTokenStream { + type Error; + + fn next_unexpanded(&mut self) -> Result, Self::Error>; + fn back_unexpanded(&mut self, token: EngineToken); + fn macro_definition(&self, token: &EngineToken) -> Option; + fn in_expanded_definition(&self) -> bool; + fn is_outer_macro(&self, token: &EngineToken) -> bool; +} + +#[derive(Clone, Copy)] +pub enum ErrorStream { + Input, + Unexpanded, +} + +pub enum MacroScanError { + Stream(E), + Macro { + token: EngineToken, + message: String, + stream: ErrorStream, + }, +} + +pub fn expand_macro( + stream: &mut S, + macro_token: EngineToken, + macro_name: &str, +) -> Result, MacroScanError> { + let Some(definition) = stream.macro_definition(¯o_token) else { + return Err(macro_error( + ¯o_token, + "macro definition is no longer active", + ErrorStream::Input, + )); + }; + if definition.is_outer && stream.in_expanded_definition() { + return Err(macro_error( + ¯o_token, + "outer macro cannot be expanded in an expanded definition", + ErrorStream::Input, + )); + } + let arguments = scan_arguments( + stream, + macro_token, + macro_name, + &definition, + definition.optional_first_default.as_deref(), + )?; + Ok(definition.instantiate(&arguments)) +} + +pub fn scan_arguments( + stream: &mut S, + macro_token: EngineToken, + macro_name: &str, + definition: &MacroDefinition, + optional_default: Option<&[EngineToken]>, +) -> Result>, MacroScanError> { + for expected in &definition.prefix { + let actual = stream + .next_unexpanded() + .map_err(MacroScanError::Stream)? + .ok_or_else(|| { + macro_error( + ¯o_token, + "macro prefix does not match its definition", + ErrorStream::Unexpanded, + ) + })?; + if actual.value != *expected { + return Err(macro_error( + &actual, + "macro prefix does not match its definition", + ErrorStream::Unexpanded, + )); + } + } + + let mut arguments = Vec::with_capacity(definition.parameters.len()); + for (index, parameter) in definition.parameters.iter().enumerate() { + let parameter_number = (index + 1) as u8; + let argument = if index == 0 { + if let Some(default) = optional_default { + read_optional_argument( + stream, + ¯o_token, + macro_name, + default, + definition.is_long, + parameter_number, + )? + } else if parameter.delimiter.is_empty() { + read_argument( + stream, + ¯o_token, + macro_name, + parameter_number, + definition.is_long, + )? + } else { + read_delimited_argument( + stream, + ¯o_token, + macro_name, + ¶meter.delimiter, + parameter_number, + definition.is_long, + )? + } + } else if parameter.delimiter.is_empty() { + read_argument( + stream, + ¯o_token, + macro_name, + parameter_number, + definition.is_long, + )? + } else { + read_delimited_argument( + stream, + ¯o_token, + macro_name, + ¶meter.delimiter, + parameter_number, + definition.is_long, + )? + }; + arguments.push(argument); + } + Ok(arguments) +} + +fn read_argument( + stream: &mut S, + macro_token: &EngineToken, + macro_name: &str, + parameter_number: u8, + is_long: bool, +) -> Result, MacroScanError> { + let first = loop { + match stream.next_unexpanded().map_err(MacroScanError::Stream)? { + Some(token) if is_space(&token.value) => continue, + Some(token) => break token, + None => { + return Err(macro_error( + macro_token, + format!("macro is missing parameter #{parameter_number}"), + ErrorStream::Unexpanded, + )); + } + } + }; + validate_argument_token(stream, &first, macro_name, parameter_number, is_long)?; + if !is_begin_group(&first.value) { + return Ok(vec![first]); + } + + let mut depth = 1usize; + let mut argument = Vec::new(); + while depth > 0 { + let Some(next) = stream.next_unexpanded().map_err(MacroScanError::Stream)? else { + return Err(macro_error( + macro_token, + format!("unterminated braced argument for parameter #{parameter_number}"), + ErrorStream::Unexpanded, + )); + }; + validate_argument_token(stream, &next, macro_name, parameter_number, is_long)?; + match next.value { + EngineTokenValue::Character { + catcode: EngineCatCode::BeginGroup, + .. + } => { + depth += 1; + argument.push(next); + } + EngineTokenValue::Character { + catcode: EngineCatCode::EndGroup, + .. + } => { + depth -= 1; + if depth > 0 { + argument.push(next); + } + } + _ => argument.push(next), + } + } + Ok(argument) +} + +fn read_delimited_argument( + stream: &mut S, + macro_token: &EngineToken, + macro_name: &str, + delimiter: &[EngineTokenValue], + parameter_number: u8, + is_long: bool, +) -> Result, MacroScanError> { + let closing_scope_depth = usize::from(matches!( + delimiter.last(), + Some(EngineTokenValue::Character { + catcode: EngineCatCode::BeginGroup, + .. + }) + )); + let mut group_depth = 0usize; + let mut argument = Vec::new(); + loop { + let Some(next) = stream.next_unexpanded().map_err(MacroScanError::Stream)? else { + return Err(macro_error( + macro_token, + format!("unterminated delimited argument for parameter #{parameter_number}"), + ErrorStream::Unexpanded, + )); + }; + if stream.is_outer_macro(&next) { + return Err(macro_error( + &next, + format!("outer macro cannot appear in an argument to {macro_name}"), + ErrorStream::Input, + )); + } + match next.value { + EngineTokenValue::Character { + catcode: EngineCatCode::BeginGroup, + .. + } => group_depth += 1, + EngineTokenValue::Character { + catcode: EngineCatCode::EndGroup, + .. + } if group_depth > 0 => group_depth -= 1, + EngineTokenValue::Character { + catcode: EngineCatCode::EndGroup, + .. + } => { + return Err(macro_error( + &next, + format!("unexpected closing group in parameter #{parameter_number}"), + ErrorStream::Unexpanded, + )); + } + _ => {} + } + argument.push(next); + + if group_depth == closing_scope_depth && argument.len() >= delimiter.len() { + let delimiter_start = argument.len() - delimiter.len(); + if argument[delimiter_start..] + .iter() + .zip(delimiter) + .all(|(token, expected)| token.value == *expected) + { + argument.truncate(delimiter_start); + return Ok(trim_outer_group(argument)); + } + } + + let last = argument.last().expect("the current token was appended"); + if !is_long + && is_par_token(last) + && (group_depth != closing_scope_depth + || !matches_delimiter_prefix(&argument, delimiter)) + { + return Err(macro_error( + last, + format!( + "paragraph ended before parameter #{parameter_number} of {macro_name} was complete" + ), + ErrorStream::Input, + )); + } + } +} + +fn read_optional_argument( + stream: &mut S, + macro_token: &EngineToken, + macro_name: &str, + default: &[EngineToken], + is_long: bool, + parameter_number: u8, +) -> Result, MacroScanError> { + let opening = loop { + match stream.next_unexpanded().map_err(MacroScanError::Stream)? { + Some(token) if is_space(&token.value) => continue, + token => break token, + } + }; + let Some(opening) = opening else { + return Ok(default.to_vec()); + }; + if !matches!( + opening.value, + EngineTokenValue::Character { + value: '[', + catcode: EngineCatCode::Other + } + ) { + stream.back_unexpanded(opening); + return Ok(default.to_vec()); + } + + let mut group_depth = 0usize; + let mut argument = Vec::new(); + loop { + let Some(next) = stream.next_unexpanded().map_err(MacroScanError::Stream)? else { + return Err(macro_error( + macro_token, + "unterminated optional macro argument; expected `]`", + ErrorStream::Unexpanded, + )); + }; + if stream.is_outer_macro(&next) { + return Err(macro_error( + &next, + format!("outer macro cannot appear in an argument to {macro_name}"), + ErrorStream::Input, + )); + } + validate_long_token(&next, macro_name, parameter_number, is_long)?; + match next.value { + EngineTokenValue::Character { + catcode: EngineCatCode::BeginGroup, + .. + } => { + group_depth += 1; + argument.push(next); + } + EngineTokenValue::Character { + catcode: EngineCatCode::EndGroup, + .. + } if group_depth > 0 => { + group_depth -= 1; + argument.push(next); + } + EngineTokenValue::Character { + catcode: EngineCatCode::EndGroup, + .. + } => { + return Err(macro_error( + &next, + "unexpected closing group in optional macro argument", + ErrorStream::Unexpanded, + )); + } + EngineTokenValue::Character { + value: ']', + catcode: EngineCatCode::Other, + } if group_depth == 0 => return Ok(argument), + _ => argument.push(next), + } + } +} + +fn validate_argument_token( + stream: &S, + argument_token: &EngineToken, + macro_name: &str, + parameter_number: u8, + is_long: bool, +) -> Result<(), MacroScanError> { + if stream.is_outer_macro(argument_token) { + return Err(macro_error( + argument_token, + format!("outer macro cannot appear in an argument to {macro_name}"), + ErrorStream::Input, + )); + } + validate_long_token(argument_token, macro_name, parameter_number, is_long) +} + +fn validate_long_token( + argument_token: &EngineToken, + macro_name: &str, + parameter_number: u8, + is_long: bool, +) -> Result<(), MacroScanError> { + if !is_long && is_par_token(argument_token) { + return Err(macro_error( + argument_token, + format!( + "paragraph ended before parameter #{parameter_number} of {macro_name} was complete" + ), + ErrorStream::Input, + )); + } + Ok(()) +} + +fn matches_delimiter_prefix(argument: &[EngineToken], delimiter: &[EngineTokenValue]) -> bool { + let max_prefix = argument.len().min(delimiter.len()); + (1..=max_prefix).rev().any(|prefix_len| { + argument[argument.len() - prefix_len..] + .iter() + .zip(&delimiter[..prefix_len]) + .all(|(token, expected)| token.value == *expected) + }) +} + +fn trim_outer_group(mut tokens: Vec) -> Vec { + if tokens.len() < 2 || !is_begin_group(&tokens[0].value) { + return tokens; + } + let mut depth = 0usize; + for (index, token) in tokens.iter().enumerate() { + match token.value { + EngineTokenValue::Character { + catcode: EngineCatCode::BeginGroup, + .. + } => depth += 1, + EngineTokenValue::Character { + catcode: EngineCatCode::EndGroup, + .. + } => { + depth -= 1; + if depth == 0 { + if index + 1 == tokens.len() { + tokens.remove(0); + tokens.pop(); + } + return tokens; + } + } + _ => {} + } + } + tokens +} + +fn is_begin_group(value: &EngineTokenValue) -> bool { + matches!( + value, + EngineTokenValue::Character { + catcode: EngineCatCode::BeginGroup, + .. + } + ) +} + +fn is_space(value: &EngineTokenValue) -> bool { + matches!( + value, + EngineTokenValue::Character { + catcode: EngineCatCode::Space, + .. + } + ) +} + +fn is_par_token(token: &EngineToken) -> bool { + matches!(&token.value, EngineTokenValue::ControlSequence(name) if name == "par") +} + +fn macro_error( + token: &EngineToken, + message: impl Into, + stream: ErrorStream, +) -> MacroScanError { + MacroScanError::Macro { + token: token.clone(), + message: message.into(), + stream, + } +} diff --git a/crates/texrra-core/src/glue.rs b/crates/texrra-core/src/glue.rs new file mode 100644 index 0000000..ba53a26 --- /dev/null +++ b/crates/texrra-core/src/glue.rs @@ -0,0 +1,77 @@ +use common::{Glue, GlueOrder, Scaled}; + +/// TeX glue with stretch and shrink orders stored as engine values. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct TeXGlue { + pub width: Scaled, + pub stretch: Scaled, + pub stretch_order: TeXGlueOrder, + pub shrink: Scaled, + pub shrink_order: TeXGlueOrder, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum TeXGlueOrder { + #[default] + Normal, + Fil, + Fill, + Filll, +} + +impl TeXGlueOrder { + pub const fn index(self) -> usize { + match self { + Self::Normal => 0, + Self::Fil => 1, + Self::Fill => 2, + Self::Filll => 3, + } + } +} + +impl From for TeXGlue { + fn from(glue: Glue) -> Self { + Self { + width: glue.width, + stretch: glue.stretch, + stretch_order: glue.stretch_order.into(), + shrink: glue.shrink, + shrink_order: glue.shrink_order.into(), + } + } +} + +impl From for Glue { + fn from(glue: TeXGlue) -> Self { + Self { + width: glue.width, + stretch: glue.stretch, + stretch_order: glue.stretch_order.into(), + shrink: glue.shrink, + shrink_order: glue.shrink_order.into(), + } + } +} + +impl From for TeXGlueOrder { + fn from(order: GlueOrder) -> Self { + match order { + GlueOrder::Normal => Self::Normal, + GlueOrder::Fil => Self::Fil, + GlueOrder::Fill => Self::Fill, + GlueOrder::Filll => Self::Filll, + } + } +} + +impl From for GlueOrder { + fn from(order: TeXGlueOrder) -> Self { + match order { + TeXGlueOrder::Normal => Self::Normal, + TeXGlueOrder::Fil => Self::Fil, + TeXGlueOrder::Fill => Self::Fill, + TeXGlueOrder::Filll => Self::Filll, + } + } +} diff --git a/crates/texrra-core/src/input.rs b/crates/texrra-core/src/input.rs new file mode 100644 index 0000000..3abb37b --- /dev/null +++ b/crates/texrra-core/src/input.rs @@ -0,0 +1,281 @@ +use std::path::{Path, PathBuf}; + +use crate::{ + EngineToken, + mouth::{CatCodeTable, InvalidCharacter, Mouth, Token}, +}; + +/// Token access required to scan a TeX input file name. +pub trait FileNameTokenStream { + type Token; + type Error; + + fn next_token(&mut self) -> Result, Self::Error>; + fn back_token(&mut self, token: Self::Token); + fn is_space(&self, token: &Self::Token) -> bool; + fn character(&self, token: &Self::Token) -> Option; +} + +#[derive(Debug)] +pub struct InputFileLocation { + pub path: String, + pub extension: Option, + pub area: Option, +} + +#[derive(Debug)] +pub enum InputPathError { + UnsupportedArea(String), + MissingWorkingDirectory, +} + +impl std::fmt::Display for InputPathError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::UnsupportedArea(area) => { + write!(formatter, "input file area `{area}` is not supported") + } + Self::MissingWorkingDirectory => formatter + .write_str("cannot resolve a relative input path without a working directory"), + } + } +} + +impl InputFileLocation { + pub fn resolve_path( + &self, + working_directory: Option<&Path>, + default_extension: &str, + ) -> Result { + if let Some(area) = &self.area { + return Err(InputPathError::UnsupportedArea(area.clone())); + } + + let mut path = working_directory.map(Path::to_path_buf).unwrap_or_default(); + path.push(&self.path); + path.set_extension(self.extension.as_deref().unwrap_or(default_extension)); + + if !path.is_absolute() { + return Err(InputPathError::MissingWorkingDirectory); + } + Ok(path) + } +} + +/// Scan and split an expanded TeX file name into its area, name, and extension. +pub fn scan_file_location( + stream: &mut S, +) -> Result { + let mut raw = String::new(); + let mut area_end = None; + let mut extension_start = None; + + loop { + let Some(token) = stream.next_token()? else { + break; + }; + if stream.is_space(&token) { + if raw.is_empty() { + continue; + } + stream.back_token(token); + break; + } + let Some(character) = stream.character(&token) else { + stream.back_token(token); + break; + }; + if character == ' ' { + break; + } + + if matches!(character, '>' | ':') { + area_end = Some(raw.len() + character.len_utf8()); + extension_start = None; + } else if character == '.' && extension_start.is_none() { + extension_start = Some(raw.len()); + } + raw.push(character); + } + + let name_start = area_end.unwrap_or(0); + let name_end = extension_start.unwrap_or(raw.len()); + Ok(InputFileLocation { + path: raw[name_start..name_end].to_string(), + extension: extension_start.map(|index| raw[index + 1..].to_string()), + area: area_end.map(|end| raw[..end].to_string()), + }) +} + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub struct InputId(u64); + +pub struct InputFrame { + id: InputId, + file_name: PathBuf, + source: String, + line_offset: usize, + priority: bool, + ended: bool, + mouth: Option, + expansion_tokens: Option>, +} + +impl InputFrame { + fn new( + id: InputId, + file_name: impl Into, + source: &str, + line_offset: usize, + priority: bool, + ) -> Self { + Self { + id, + file_name: file_name.into(), + source: source.to_string(), + line_offset, + priority, + ended: false, + mouth: Some(Mouth::new(source)), + expansion_tokens: None, + } + } + + fn new_expansion(id: InputId, tokens: Vec) -> Self { + Self { + id, + file_name: PathBuf::from(""), + source: String::new(), + line_offset: 0, + priority: true, + ended: false, + mouth: None, + expansion_tokens: Some(tokens.into_iter().rev().collect()), + } + } + + pub fn id(&self) -> InputId { + self.id + } + + pub fn file_name(&self) -> &Path { + &self.file_name + } + + pub fn source(&self) -> &str { + &self.source + } + + pub fn line_offset(&self) -> usize { + self.line_offset + } + + pub fn is_priority(&self) -> bool { + self.priority + } + + pub fn is_expansion(&self) -> bool { + self.expansion_tokens.is_some() + } + + pub fn next_expansion_token(&mut self) -> Option { + self.expansion_tokens.as_mut()?.pop() + } + + pub fn has_expansion_tokens(&self) -> bool { + self.expansion_tokens + .as_ref() + .is_some_and(|tokens| !tokens.is_empty()) + } + + pub fn is_source(&self) -> bool { + self.mouth.is_some() + } + + pub fn is_ended(&self) -> bool { + self.ended + } + + pub fn end(&mut self) { + self.ended = true; + } + + pub fn next_token( + &mut self, + catcodes: &CatCodeTable, + ) -> Result, InvalidCharacter> { + self.mouth + .as_mut() + .expect("token expansion frames do not own a mouth") + .next_token(catcodes) + } +} + +#[derive(Default)] +pub struct InputStack { + frames: Vec, + next_id: u64, +} + +impl InputStack { + pub fn clear(&mut self) { + self.frames.clear(); + } + + pub fn push( + &mut self, + file_name: impl Into, + source: &str, + line_offset: usize, + priority: bool, + ) -> InputId { + let id = InputId(self.next_id); + self.next_id = self.next_id.wrapping_add(1); + self.frames.push(InputFrame::new( + id, + file_name, + source, + line_offset, + priority, + )); + id + } + + /// Push an already-tokenized macro replacement before the current input. + /// Tokens are supplied in the order in which TeX should read them. + pub fn push_expansion_tokens(&mut self, tokens: Vec) -> InputId { + let id = InputId(self.next_id); + self.next_id = self.next_id.wrapping_add(1); + if !tokens.is_empty() { + self.frames.push(InputFrame::new_expansion(id, tokens)); + } + id + } + + pub fn pop(&mut self) -> Option { + self.frames.pop() + } + + pub fn push_frame(&mut self, frame: InputFrame) { + self.frames.push(frame); + } + + pub fn last(&self) -> Option<&InputFrame> { + self.frames.last() + } + + pub fn last_mut(&mut self) -> Option<&mut InputFrame> { + self.frames.last_mut() + } + + pub fn last_source_mut(&mut self) -> Option<&mut InputFrame> { + self.frames.iter_mut().rev().find(|frame| frame.is_source()) + } + + pub fn external_depth(&self) -> usize { + self.frames + .iter() + .filter(|frame| !frame.is_priority()) + .count() + } +} diff --git a/crates/texrra-core/src/integer.rs b/crates/texrra-core/src/integer.rs new file mode 100644 index 0000000..d02da81 --- /dev/null +++ b/crates/texrra-core/src/integer.rs @@ -0,0 +1,215 @@ +use crate::CatCode; + +/// Token access required by TeX's integer scanner. +pub trait IntegerTokenStream { + type Token: Clone; + type Error; + + fn next_token(&mut self) -> Result, Self::Error>; + fn back_token(&mut self, token: Self::Token); + fn character(&self, token: &Self::Token) -> Option<(char, CatCode)>; + fn is_space(&self, token: &Self::Token) -> bool; + fn is_command_reference(&self, token: &Self::Token) -> bool; + fn control_sequence_name(&self, token: &Self::Token) -> Option; + fn scan_internal_integer(&mut self, token: Self::Token) -> Result, Self::Error>; +} + +/// Failure while scanning an integer from a TeX token stream. +#[derive(Debug)] +pub enum IntegerScanError { + Stream(Error), + CompatibilityRequired, + MissingNumber(Option), + TooLarge { + token: Option, + negative: bool, + }, +} + +/// The scanned value and first token, retained for source diagnostics. +#[derive(Clone, Debug)] +pub struct ScannedInteger { + pub value: i32, + pub first_token: Token, +} + +pub fn scan_integer( + stream: &mut S, +) -> Result> { + scan_integer_with_token(stream).map(|scanned| scanned.value) +} + +pub fn scan_integer_with_token( + stream: &mut S, +) -> Result, IntegerScanError> { + let (negative, first) = scan_signs(stream)?; + let first_token = first.clone(); + let (value, scan_optional_space) = match stream.character(&first) { + Some(('\'', CatCode::Other)) => (scan_radix_integer(stream, first, 8, negative)?, true), + Some(('"', CatCode::Other)) => (scan_radix_integer(stream, first, 16, negative)?, true), + Some(('`', CatCode::Other)) => (scan_character_integer(stream, first)?, false), + Some((character, CatCode::Other)) if character.is_ascii_digit() => { + (scan_decimal_integer(stream, first, negative)?, true) + } + _ if stream.is_command_reference(&first) => match stream + .scan_internal_integer(first) + .map_err(IntegerScanError::Stream)? + { + Some(value) => (value, false), + None => return Err(IntegerScanError::CompatibilityRequired), + }, + _ => return Err(IntegerScanError::MissingNumber(Some(first))), + }; + + if scan_optional_space { + consume_optional_space(stream)?; + } + let value = if negative { + value.wrapping_mul(-1) + } else { + value + }; + Ok(ScannedInteger { value, first_token }) +} + +fn scan_signs( + stream: &mut S, +) -> Result<(bool, S::Token), IntegerScanError> { + let mut negative = false; + loop { + let Some(token) = next_token(stream)? else { + return Err(IntegerScanError::MissingNumber(None)); + }; + if stream.is_space(&token) { + continue; + } + if let Some((character, CatCode::Other)) = stream.character(&token) { + match character { + '+' => continue, + '-' => { + negative = !negative; + continue; + } + _ => return Ok((negative, token)), + } + } + return Ok((negative, token)); + } +} + +fn scan_decimal_integer( + stream: &mut S, + first: S::Token, + negative: bool, +) -> Result> { + let mut value = u64::from(digit(stream, &first).expect("first token is a decimal digit")); + loop { + let Some(token) = next_token(stream)? else { + break; + }; + let Some(digit) = digit(stream, &token) else { + stream.back_token(token); + break; + }; + value = value + .checked_mul(10) + .and_then(|value| value.checked_add(u64::from(digit))) + .ok_or_else(|| IntegerScanError::TooLarge { + token: Some(first.clone()), + negative, + })?; + } + i32::try_from(value).map_err(|_| IntegerScanError::TooLarge { + token: Some(first), + negative, + }) +} + +fn scan_radix_integer( + stream: &mut S, + first: S::Token, + radix: u8, + negative: bool, +) -> Result> { + let mut value = 0_u64; + let mut digit_count = 0; + loop { + let Some(token) = next_token(stream)? else { + break; + }; + let digit = match stream.character(&token) { + Some((character, CatCode::Other | CatCode::Letter)) => { + character.to_digit(u32::from(radix)) + } + _ => None, + }; + let Some(digit) = digit else { + stream.back_token(token); + break; + }; + value = value + .checked_mul(u64::from(radix)) + .and_then(|value| value.checked_add(u64::from(digit))) + .ok_or_else(|| IntegerScanError::TooLarge { + token: Some(first.clone()), + negative, + })?; + digit_count += 1; + } + if digit_count == 0 || value > i32::MAX as u64 { + return Err(IntegerScanError::TooLarge { + token: Some(first), + negative, + }); + } + Ok(value as i32) +} + +fn scan_character_integer( + stream: &mut S, + first: S::Token, +) -> Result> { + let character = next_token(stream)? + .and_then(|token| { + stream + .character(&token) + .map(|(character, _)| character) + .or_else(|| { + stream.control_sequence_name(&token).and_then(|name| { + (name.chars().count() == 1) + .then(|| name.chars().next()) + .flatten() + }) + }) + }) + .ok_or(IntegerScanError::CompatibilityRequired)?; + consume_optional_space(stream)?; + i32::try_from(character as u32).map_err(|_| IntegerScanError::TooLarge { + token: Some(first), + negative: false, + }) +} + +fn consume_optional_space( + stream: &mut S, +) -> Result<(), IntegerScanError> { + if let Some(token) = next_token(stream)? { + if !stream.is_space(&token) { + stream.back_token(token); + } + } + Ok(()) +} + +fn next_token( + stream: &mut S, +) -> Result, IntegerScanError> { + stream.next_token().map_err(IntegerScanError::Stream) +} + +fn digit(stream: &S, token: &S::Token) -> Option { + match stream.character(token) { + Some((character, CatCode::Other)) => character.to_digit(10).map(|digit| digit as u8), + _ => None, + } +} diff --git a/crates/texrra-core/src/layout_primitive.rs b/crates/texrra-core/src/layout_primitive.rs new file mode 100644 index 0000000..f9ca342 --- /dev/null +++ b/crates/texrra-core/src/layout_primitive.rs @@ -0,0 +1,54 @@ +/// Layout primitives whose scanning semantics are independent of a runtime VM. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum LayoutPrimitive { + ParagraphBreak, + LineBreak, + PageBreak, + Penalty, + Kern, + HorizontalSkip, + VerticalSkip, +} + +/// Typed effect produced after a layout primitive has scanned its operands. +pub enum LayoutEffect { + ParagraphBreak, + LineBreak, + PageBreak, + Penalty(i32), + Kern(Dimension), + HorizontalGlue(Glue), + VerticalGlue(Glue), +} + +/// Input and output boundary supplied by a compiler adapter. +pub trait LayoutPrimitiveInput { + type Error; + type Dimension; + type Glue; + + fn scan_integer(&mut self) -> Result; + fn scan_dimension(&mut self) -> Result; + fn scan_glue(&mut self) -> Result; + fn emit( + &mut self, + effect: LayoutEffect, + ) -> Result<(), Self::Error>; +} + +/// Execute one layout primitive by scanning its operands and emitting one event. +pub fn execute( + primitive: LayoutPrimitive, + input: &mut S, +) -> Result<(), S::Error> { + let effect = match primitive { + LayoutPrimitive::ParagraphBreak => LayoutEffect::ParagraphBreak, + LayoutPrimitive::LineBreak => LayoutEffect::LineBreak, + LayoutPrimitive::PageBreak => LayoutEffect::PageBreak, + LayoutPrimitive::Penalty => LayoutEffect::Penalty(input.scan_integer()?), + LayoutPrimitive::Kern => LayoutEffect::Kern(input.scan_dimension()?), + LayoutPrimitive::HorizontalSkip => LayoutEffect::HorizontalGlue(input.scan_glue()?), + LayoutPrimitive::VerticalSkip => LayoutEffect::VerticalGlue(input.scan_glue()?), + }; + input.emit(effect) +} diff --git a/crates/texrra-core/src/lib.rs b/crates/texrra-core/src/lib.rs new file mode 100644 index 0000000..bff8751 --- /dev/null +++ b/crates/texrra-core/src/lib.rs @@ -0,0 +1,483 @@ +//! Primitive TeX value types shared by the Rust engine and compatibility adapters. + +use CatCode::*; + +pub mod assignment_scope; +pub mod command; +pub mod document; +pub mod document_parser; +pub mod environment; +pub mod expanded; +pub mod expansion; +pub mod glue; +pub mod input; +pub mod integer; +pub mod layout_primitive; +pub mod macros; +pub mod math_alphabet; +pub mod math_code; +pub mod math_constants; +pub mod math_expr; +pub mod math_glyph; +pub mod math_layout; +pub mod math_list; +pub mod math_lowering; +pub mod math_mode; +pub mod math_parser; +pub mod math_style; +pub mod mouth; +pub mod references; +pub mod source; +pub mod state; + +pub use glue::{TeXGlue, TeXGlueOrder}; +pub use math_list::{MathBoundary, MathListContext, MathSpacingKind}; +pub use math_style::{MathStyle, MathStyleCommand}; + +/// TeX math atom class, used by noad construction and inter-atom spacing. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum MathClass { + Ordinary, + Operator, + Binary, + Relation, + Opening, + Closing, + Punctuation, + Inner, +} + +impl MathClass { + pub fn index(self) -> usize { + match self { + Self::Ordinary => 0, + Self::Operator => 1, + Self::Binary => 2, + Self::Relation => 3, + Self::Opening => 4, + Self::Closing => 5, + Self::Punctuation => 6, + Self::Inner => 7, + } + } +} + +/// An engine-owned TeX command name, independent of any runtime interner. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum EngineCommandName { + /// A named control sequence such as `\\par`. + ControlSequence(String), + /// An active character token. + ActiveCharacter(char), +} + +/// The value and category code of an engine-owned TeX token. +#[derive(Clone, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum EngineTokenValue { + /// A control sequence that may be expanded or executed. + ControlSequence(String), + /// A character token with the category code captured by the mouth. + Character { value: char, catcode: CatCode }, + /// An active character, which behaves like a control sequence. + Active(char), +} + +/// A TeX token with a stable source-trace handle owned by the engine. +#[derive(Clone, Debug)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct EngineToken { + /// The token's semantic value. + pub value: EngineTokenValue, + /// Opaque handle used by the application adapter to recover source data. + pub trace_id: u32, +} + +/// Enum representing all 16 category codes in TeX. +/// +/// Each variant's documentation contains an example character which is mapped to that category code in plainTeX. +#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum CatCode { + /// Marks the beginning of a control sequence. + /// Example: `\`. + /// + /// This category code is never seen outside of the lexer. + Escape = 0, + /// Begins a new group. + /// Example: `{`. + BeginGroup = 1, + /// Ends an existing new group. + /// Example: `}`. + EndGroup = 2, + /// Starts or ends math mode. + /// Example: `$`. + MathShift = 3, + /// Used in typesetting tables to align cells. + /// Example: `&`. + AlignmentTab = 4, + /// Marks a new line in the input. + /// Example: `\n`. + /// + /// This code behaves similarly to [Space], but has two additional properties. + /// First, two or more consecutive new lines, modulo intervening [Space] characters, create a `\par` control sequence + /// instead of a regular space. + /// Second, this code terminates a comment that started with a [Comment] character. + /// + /// This category code is never seen outside of the lexer. + EndOfLine = 5, + /// Marks the beginning of a parameter number. + /// It must generally be followed by a digit. + /// Example: `#`. + Parameter = 6, + /// Puts following character or group in a superscript. + /// Example: `^`. + Superscript = 7, + /// Puts following character or group in a subscript. + /// Example: `_`. + Subscript = 8, + /// Character that is ignored by the lexer. + /// Example: ASCII null (0). + /// + /// This category code is never seen outside of the lexer. + Ignored = 9, + /// Whitespace. Example: ` `. + Space = 10, + /// A character that can be used as a control sequence name. + /// Examples: `[a-zA-z]`. + Letter = 11, + /// A character than cannot be used as a control sequence name. + /// Example: `@`. + #[default] + Other = 12, + /// A single character that behaves like a control sequence. + /// Example: `~`. + Active = 13, + /// Marks the beginning of a comment. + /// All characters until the next [EndOfLine] are ignored. + /// Example: `%`. + /// + /// This category code is never seen outside of the lexer. + Comment = 14, + /// An invalid character. + /// If this is encountered in the input, the lexer will return an error. + /// Example: ASCII delete (127). + /// + /// This category code is never seen outside of the lexer. + Invalid = 15, +} + +/// A TeX math code value. +/// +/// Its inner value is in the range 0 through 32768. The upper bound represents +/// the math-active value used by `\mathcode`. +#[derive(Clone, Copy, Debug, Default)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct MathCode(pub u16); + +impl MathCode { + /// The largest value accepted by the TeX `\mathcode` scanner. + pub const MAX: usize = 32768; +} + +impl TryFrom for CatCode { + type Error = (); + + fn try_from(value: u8) -> Result { + match value { + 0 => Ok(Escape), + 1 => Ok(BeginGroup), + 2 => Ok(EndGroup), + 3 => Ok(MathShift), + 4 => Ok(AlignmentTab), + 5 => Ok(EndOfLine), + 6 => Ok(Parameter), + 7 => Ok(Superscript), + 8 => Ok(Subscript), + 9 => Ok(Ignored), + 10 => Ok(Space), + 11 => Ok(Letter), + 12 => Ok(Other), + 13 => Ok(Active), + 14 => Ok(Comment), + 15 => Ok(Invalid), + _ => Err(()), + } + } +} + +impl std::fmt::Display for CatCode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{} ({})", + *self as u8, + match self { + Escape => "escape", + BeginGroup => "begin group", + EndGroup => "end group", + MathShift => "math shift", + AlignmentTab => "alignment tab", + EndOfLine => "end of line", + Parameter => "parameter", + Superscript => "superscript", + Subscript => "subscript", + Ignored => "ignored", + Space => "space", + Letter => "letter", + Other => "other", + Active => "active", + Comment => "comment", + Invalid => "invalid", + } + )?; + Ok(()) + } +} + +impl CatCode { + /// Default category codes in INITEX for all ASCII characters. + /// + /// To find the category code for an ASCII character, + /// convert it to an integer and use it as an index for the array. + /// + /// This list was compiled by reading the source code TeX '82, + /// specifically section 232 in the "TeX: the program". + /// These defaults are also described in the TeXBook p343. + pub const INITEX_DEFAULTS: [CatCode; 128] = [ + Ignored, // ASCII null + Other, Other, Other, Other, Other, Other, Other, Other, Other, + EndOfLine, // carriage return + Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, + Other, Other, Other, Other, Other, Other, Other, Other, Space, // space + Other, Other, Other, Other, Comment, // % + Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, + Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, + Other, Letter, // A + Letter, // B + Letter, // C + Letter, // D + Letter, // E + Letter, // F + Letter, // G + Letter, // H + Letter, // I + Letter, // J + Letter, // K + Letter, // L + Letter, // M + Letter, // N + Letter, // O + Letter, // P + Letter, // Q + Letter, // R + Letter, // S + Letter, // T + Letter, // U + Letter, // V + Letter, // W + Letter, // X + Letter, // Y + Letter, // Z + Other, Escape, // \ + Other, Other, Other, Other, Letter, // a + Letter, // b + Letter, // c + Letter, // d + Letter, // e + Letter, // f + Letter, // g + Letter, // h + Letter, // i + Letter, // j + Letter, // k + Letter, // l + Letter, // m + Letter, // n + Letter, // o + Letter, // p + Letter, // q + Letter, // r + Letter, // s + Letter, // t + Letter, // u + Letter, // v + Letter, // w + Letter, // x + Letter, // y + Letter, // z + Other, Other, Other, Other, Invalid, // ASCII delete + ]; + + /// Default category codes in plainTeX for all ASCII characters. + /// + /// To find the category code for an ASCII character, + /// convert it to an integer and use it as an index for the array. + /// + /// This list was compiled by starting with [INITEX_DEFAULTS](CatCode::INITEX_DEFAULTS) and then applying + /// all category code changes in the plainTeX format. + /// These changes are described on p343 of the TeXBook. + pub const PLAIN_TEX_DEFAULTS: [CatCode; 128] = [ + Ignored, // ASCII null + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Space, // horizontal tab (\t) + EndOfLine, // line feed (\n) + Other, + Active, // ASCII form-feed + EndOfLine, // carriage return (\r) + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Space, // space + Other, + Other, + Parameter, // # + MathShift, // $ + Comment, // % + AlignmentTab, // & + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Other, + Letter, // A + Letter, // B + Letter, // C + Letter, // D + Letter, // E + Letter, // F + Letter, // G + Letter, // H + Letter, // I + Letter, // J + Letter, // K + Letter, // L + Letter, // M + Letter, // N + Letter, // O + Letter, // P + Letter, // Q + Letter, // R + Letter, // S + Letter, // T + Letter, // U + Letter, // V + Letter, // W + Letter, // X + Letter, // Y + Letter, // Z + Other, + Escape, // \ + Other, + Superscript, // ^ + Subscript, // _ + Other, + Letter, // a + Letter, // b + Letter, // c + Letter, // d + Letter, // e + Letter, // f + Letter, // g + Letter, // h + Letter, // i + Letter, // j + Letter, // k + Letter, // l + Letter, // m + Letter, // n + Letter, // o + Letter, // p + Letter, // q + Letter, // r + Letter, // s + Letter, // t + Letter, // u + Letter, // v + Letter, // w + Letter, // x + Letter, // y + Letter, // z + BeginGroup, // { + Other, + EndGroup, // } + Active, // ~ + Invalid, // ASCII delete + ]; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn serialize_and_deserialize_cat_code() { + let all_raw_cat_codes = vec![ + CatCode::BeginGroup, + CatCode::EndGroup, + CatCode::MathShift, + CatCode::AlignmentTab, + CatCode::Parameter, + CatCode::Superscript, + CatCode::Subscript, + CatCode::Space, + CatCode::Letter, + CatCode::Other, + CatCode::Active, + CatCode::Escape, + CatCode::EndOfLine, + CatCode::Ignored, + CatCode::Comment, + CatCode::Invalid, + ]; + for cat_code in all_raw_cat_codes { + let u: u8 = cat_code as u8; + let recovered: CatCode = u.try_into().unwrap(); + assert_eq!(recovered, cat_code); + } + } +} diff --git a/crates/texrra-core/src/macros.rs b/crates/texrra-core/src/macros.rs new file mode 100644 index 0000000..5b54307 --- /dev/null +++ b/crates/texrra-core/src/macros.rs @@ -0,0 +1,477 @@ +use std::collections::HashMap; + +use crate::{CatCode as EngineCatCode, EngineCommandName, EngineToken, EngineTokenValue}; + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct MacroDefinition { + pub prefix: Vec, + pub parameters: Vec, + pub optional_first_default: Option>, + pub replacement: Vec, + #[serde(default)] + pub is_long: bool, + #[serde(default)] + pub is_outer: bool, +} + +impl MacroDefinition { + pub fn instantiate(&self, arguments: &[Vec]) -> Vec { + let mut expansion = Vec::new(); + for item in &self.replacement { + match item { + Replacement::Tokens(tokens) => { + expansion.extend(tokens.iter().cloned()); + } + Replacement::Parameter(index) => { + expansion.extend(arguments[*index].iter().cloned()); + } + } + } + expansion + } +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct MacroParameter { + pub delimiter: Vec, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub enum Replacement { + Tokens(Vec), + Parameter(usize), +} + +pub trait MacroDefinitionTokenStream { + type Error; + + fn next_unexpanded(&mut self) -> Result, Self::Error>; + fn is_outer_macro(&self, token: &EngineToken) -> bool; +} + +#[derive(Clone, Copy)] +pub enum MacroDefinitionErrorStream { + Input, + Unexpanded, +} + +pub enum MacroDefinitionScanError { + Stream(E), + Macro { + token: EngineToken, + message: String, + stream: MacroDefinitionErrorStream, + }, +} + +pub struct ScannedMacroDefinition { + pub target: EngineToken, + pub parameter_text: Vec, + pub replacement_text: Vec, +} + +pub fn scan_tex_macro_definition( + stream: &mut S, + command: &EngineToken, +) -> Result> { + let target = loop { + let Some(token) = stream + .next_unexpanded() + .map_err(MacroDefinitionScanError::Stream)? + else { + return Err(macro_definition_error( + command, + "macro definition expects a control sequence", + MacroDefinitionErrorStream::Input, + )); + }; + if is_space(&token) { + continue; + } + break token; + }; + + if !is_command(&target) { + return Err(macro_definition_error( + &target, + "macro definition expects a control sequence or active character", + MacroDefinitionErrorStream::Input, + )); + } + + let mut parameter_text = Vec::new(); + loop { + let Some(next) = stream + .next_unexpanded() + .map_err(MacroDefinitionScanError::Stream)? + else { + return Err(macro_definition_error( + command, + "unterminated macro definition", + MacroDefinitionErrorStream::Unexpanded, + )); + }; + reject_outer_macro(stream, &next)?; + + if is_begin_group(&next) { + let replacement_text = read_braced_replacement(stream, command)?; + return Ok(ScannedMacroDefinition { + target, + parameter_text, + replacement_text, + }); + } + if is_end_group(&next) { + return Err(macro_definition_error( + &next, + "unexpected end group while reading macro parameters", + MacroDefinitionErrorStream::Input, + )); + } + if is_parameter(&next) { + let Some(parameter_part) = stream + .next_unexpanded() + .map_err(MacroDefinitionScanError::Stream)? + else { + return Err(macro_definition_error( + command, + "unterminated macro parameter text", + MacroDefinitionErrorStream::Unexpanded, + )); + }; + reject_outer_macro(stream, ¶meter_part)?; + if is_begin_group(¶meter_part) { + parameter_text.push(parameter_part.clone()); + let mut replacement_text = + read_replacement_after_special_open(stream, command, ¶meter_part)?; + replacement_text.push(parameter_part); + return Ok(ScannedMacroDefinition { + target, + parameter_text, + replacement_text, + }); + } + parameter_text.push(next); + parameter_text.push(parameter_part); + continue; + } + parameter_text.push(next); + } +} + +fn read_braced_replacement( + stream: &mut S, + command: &EngineToken, +) -> Result, MacroDefinitionScanError> { + let mut depth = 1usize; + let mut replacement = Vec::new(); + loop { + let Some(next) = stream + .next_unexpanded() + .map_err(MacroDefinitionScanError::Stream)? + else { + return Err(macro_definition_error( + command, + "unterminated braced command argument", + MacroDefinitionErrorStream::Input, + )); + }; + reject_outer_macro(stream, &next)?; + if is_begin_group(&next) { + depth += 1; + replacement.push(next); + } else if is_end_group(&next) { + depth -= 1; + if depth == 0 { + return Ok(replacement); + } + replacement.push(next); + } else { + replacement.push(next); + } + } +} + +fn read_replacement_after_special_open( + stream: &mut S, + command: &EngineToken, + opening: &EngineToken, +) -> Result, MacroDefinitionScanError> { + let mut depth = 0usize; + let mut replacement = Vec::new(); + loop { + let Some(next) = stream + .next_unexpanded() + .map_err(MacroDefinitionScanError::Stream)? + else { + let delimiter = match opening.value { + EngineTokenValue::Character { value, .. } => value, + _ => '{', + }; + return Err(macro_definition_error( + command, + &format!("unterminated macro replacement after special delimiter `{delimiter}`"), + MacroDefinitionErrorStream::Unexpanded, + )); + }; + reject_outer_macro(stream, &next)?; + if is_begin_group(&next) { + depth += 1; + replacement.push(next); + } else if is_end_group(&next) { + if depth == 0 { + return Ok(replacement); + } + depth -= 1; + replacement.push(next); + } else { + replacement.push(next); + } + } +} + +fn reject_outer_macro( + stream: &S, + token: &EngineToken, +) -> Result<(), MacroDefinitionScanError> { + if stream.is_outer_macro(token) { + return Err(macro_definition_error( + token, + "outer macro is forbidden while scanning a definition or argument", + MacroDefinitionErrorStream::Input, + )); + } + Ok(()) +} + +fn macro_definition_error( + token: &EngineToken, + message: impl Into, + stream: MacroDefinitionErrorStream, +) -> MacroDefinitionScanError { + MacroDefinitionScanError::Macro { + token: token.clone(), + message: message.into(), + stream, + } +} + +fn is_space(token: &EngineToken) -> bool { + matches!( + token.value, + EngineTokenValue::Character { + catcode: EngineCatCode::Space, + .. + } + ) +} + +fn is_begin_group(token: &EngineToken) -> bool { + matches!( + token.value, + EngineTokenValue::Character { + catcode: EngineCatCode::BeginGroup, + .. + } + ) +} + +fn is_end_group(token: &EngineToken) -> bool { + matches!( + token.value, + EngineTokenValue::Character { + catcode: EngineCatCode::EndGroup, + .. + } + ) +} + +fn is_parameter(token: &EngineToken) -> bool { + matches!( + token.value, + EngineTokenValue::Character { + catcode: EngineCatCode::Parameter, + .. + } + ) +} + +fn is_command(token: &EngineToken) -> bool { + matches!( + token.value, + EngineTokenValue::ControlSequence(_) | EngineTokenValue::Active(_) + ) +} + +pub struct MacroDefinitionParseError { + pub token_index: usize, + pub message: String, +} + +pub fn parse_tex_macro_parameters( + parameter_text: &[EngineTokenValue], +) -> Result<(Vec, Vec), MacroDefinitionParseError> { + let mut prefix = Vec::new(); + let mut parameters: Vec = Vec::new(); + let mut between = Vec::new(); + let mut cursor = 0; + while cursor < parameter_text.len() { + let current = ¶meter_text[cursor]; + if !is_parameter_value(current) { + between.push(current.clone()); + cursor += 1; + continue; + } + let Some(number_token) = parameter_text.get(cursor + 1) else { + return Err(MacroDefinitionParseError { + token_index: cursor, + message: "parameter marker must be followed by a number from 1 to 9".into(), + }); + }; + let expected_number = parameters.len() + 1; + let valid_number = token_character(number_token) + .filter(char::is_ascii_digit) + .and_then(|character| character.to_digit(10)) + .is_some_and(|number| number as usize == expected_number); + if expected_number > 9 || !valid_number { + return Err(MacroDefinitionParseError { + token_index: cursor + 1, + message: format!("expected macro parameter #{expected_number}"), + }); + } + if let Some(previous) = parameters.last_mut() { + previous.delimiter = std::mem::take(&mut between); + } else { + prefix = std::mem::take(&mut between); + } + parameters.push(MacroParameter { + delimiter: Vec::new(), + }); + cursor += 2; + } + if let Some(last) = parameters.last_mut() { + last.delimiter = between; + } else { + prefix = between; + } + Ok((prefix, parameters)) +} + +pub fn parse_macro_replacement( + replacement: &[EngineToken], + arity: u8, +) -> Result, MacroDefinitionParseError> { + let mut result = Vec::new(); + let mut literal_tokens = Vec::new(); + let mut cursor = 0; + while cursor < replacement.len() { + let current = &replacement[cursor]; + if !is_parameter_value(¤t.value) { + literal_tokens.push(current.clone()); + cursor += 1; + continue; + } + + let Some(next) = replacement.get(cursor + 1) else { + return Err(MacroDefinitionParseError { + token_index: cursor, + message: "parameter marker must be followed by `#` or a parameter number".into(), + }); + }; + if is_parameter_value(&next.value) { + literal_tokens.push(next.clone()); + cursor += 2; + continue; + } + let parameter_number = token_character(&next.value) + .filter(char::is_ascii_digit) + .and_then(|character| character.to_digit(10)) + .and_then(|number| u8::try_from(number).ok()) + .filter(|number| *number > 0 && *number <= arity) + .ok_or_else(|| MacroDefinitionParseError { + token_index: cursor + 1, + message: format!("parameter number must be between 1 and {arity}"), + })?; + + if !literal_tokens.is_empty() { + result.push(Replacement::Tokens(std::mem::take(&mut literal_tokens))); + } + result.push(Replacement::Parameter(usize::from(parameter_number - 1))); + cursor += 2; + } + if !literal_tokens.is_empty() { + result.push(Replacement::Tokens(literal_tokens)); + } + Ok(result) +} + +fn is_parameter_value(value: &EngineTokenValue) -> bool { + matches!( + value, + EngineTokenValue::Character { + catcode: EngineCatCode::Parameter, + .. + } + ) +} + +fn token_character(value: &EngineTokenValue) -> Option { + match value { + EngineTokenValue::Character { value, .. } => Some(*value), + EngineTokenValue::ControlSequence(_) | EngineTokenValue::Active(_) => None, + } +} + +#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] +pub struct MacroTable { + definitions: HashMap, + groups: Vec>>, +} + +impl MacroTable { + pub fn get(&self, name: &EngineCommandName) -> Option<&MacroDefinition> { + self.definitions.get(name) + } + + pub fn define(&mut self, name: EngineCommandName, definition: MacroDefinition, global: bool) { + self.prepare_assignment(&name, global); + self.definitions.insert(name, definition); + } + + pub fn remove(&mut self, name: EngineCommandName, global: bool) { + self.prepare_assignment(&name, global); + self.definitions.remove(&name); + } + + fn prepare_assignment(&mut self, name: &EngineCommandName, global: bool) { + if global { + for group in &mut self.groups { + group.remove(name); + } + } else if let Some(group) = self.groups.last_mut() { + group + .entry(name.clone()) + .or_insert_with(|| self.definitions.get(name).cloned()); + } + } + + pub fn begin_group(&mut self) { + self.groups.push(HashMap::new()); + } + + pub fn end_group(&mut self) { + let Some(group) = self.groups.pop() else { + return; + }; + for (name, previous) in group { + match previous { + Some(definition) => { + self.definitions.insert(name, definition); + } + None => { + self.definitions.remove(&name); + } + } + } + } +} diff --git a/crates/texrra-core/src/math_alphabet.rs b/crates/texrra-core/src/math_alphabet.rs new file mode 100644 index 0000000..8da96cc --- /dev/null +++ b/crates/texrra-core/src/math_alphabet.rs @@ -0,0 +1,609 @@ +use std::path::Path; + +use crate::math_expr::{MathExpr, MathFontFamilies, MathFontStyle}; +use crate::{MathClass, MathStyle}; + +/// A Unicode mathematical alphabet selected by a TeX math font command. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathAlphabet { + Bold, + BoldItalic, + BoldScript, + BoldFraktur, + Italic, + Script, + Fraktur, + DoubleStruck, + SansSerif, + SansSerifBold, + SansSerifItalic, + SansSerifBoldItalic, +} + +/// Selects a Unicode mathematical alphabet for a TeX math font style. +pub fn for_font_style(font: MathFontStyle, bold: bool, italic: bool) -> Option { + Some(match font { + MathFontStyle::Bold => { + if italic { + MathAlphabet::BoldItalic + } else { + MathAlphabet::Bold + } + } + MathFontStyle::BoldRoman => MathAlphabet::Bold, + MathFontStyle::Italic => MathAlphabet::Italic, + MathFontStyle::Calligraphic => { + if bold { + MathAlphabet::BoldScript + } else { + MathAlphabet::Script + } + } + MathFontStyle::Fraktur => { + if bold { + MathAlphabet::BoldFraktur + } else { + MathAlphabet::Fraktur + } + } + MathFontStyle::Blackboard => MathAlphabet::DoubleStruck, + MathFontStyle::SansSerif => match (bold, italic) { + (false, false) => MathAlphabet::SansSerif, + (true, false) => MathAlphabet::SansSerifBold, + (false, true) => MathAlphabet::SansSerifItalic, + (true, true) => MathAlphabet::SansSerifBoldItalic, + }, + MathFontStyle::Monospace | MathFontStyle::Roman | MathFontStyle::Text => return None, + }) +} + +/// Applies a Unicode math alphabet to ordinary atoms, consulting the backend +/// only for glyph availability in the selected family and default math font. +pub fn transform_expression( + expression: &MathExpr, + alphabet: MathAlphabet, + bold: bool, + italic: bool, + math_style: MathStyle, + has_selected_font_glyph: impl Fn(&Path, char) -> bool, + has_default_math_glyph: impl Fn(char) -> bool, +) -> MathExpr { + fn transform( + expression: &MathExpr, + alphabet: MathAlphabet, + bold: bool, + italic: bool, + math_style: MathStyle, + has_selected_font_glyph: &impl Fn(&Path, char) -> bool, + has_default_math_glyph: &impl Fn(char) -> bool, + ) -> MathExpr { + match expression { + MathExpr::Spanned { + location, + expression, + } => MathExpr::Spanned { + location: location.clone(), + expression: Box::new(transform( + expression, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + }, + MathExpr::Styled { .. } => expression.clone(), + MathExpr::Classified { class, body } => MathExpr::Classified { + class: *class, + body: Box::new(transform( + body, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + }, + MathExpr::Phantom { kind, body } => MathExpr::Phantom { + kind: *kind, + body: Box::new(transform( + body, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + }, + MathExpr::Accent { + position, + body, + family, + math_fonts, + } => MathExpr::Accent { + position: *position, + body: Box::new(transform( + body, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + family: *family, + math_fonts: math_fonts.clone(), + }, + MathExpr::Sequence(items) => MathExpr::Sequence( + items + .iter() + .map(|item| { + transform( + item, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + ) + }) + .collect(), + ), + MathExpr::Alignment { + rows, + alignment, + baseline, + math_fonts, + cell_style, + row_spacing, + } => MathExpr::Alignment { + rows: rows + .iter() + .map(|row| { + row.iter() + .map(|item| { + transform( + item, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + ) + }) + .collect() + }) + .collect(), + alignment: alignment.clone(), + baseline: *baseline, + math_fonts: math_fonts.clone(), + cell_style: *cell_style, + row_spacing: *row_spacing, + }, + MathExpr::Fraction { + numerator, + denominator, + style, + has_rule, + rule_thickness, + math_fonts, + } => MathExpr::Fraction { + numerator: Box::new(transform( + numerator, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + denominator: Box::new(transform( + denominator, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + style: *style, + has_rule: *has_rule, + rule_thickness: *rule_thickness, + math_fonts: math_fonts.clone(), + }, + MathExpr::MathChoice { + display, + text, + script, + scriptscript, + } => MathExpr::MathChoice { + display: Box::new(transform( + display, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + text: Box::new(transform( + text, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + script: Box::new(transform( + script, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + scriptscript: Box::new(transform( + scriptscript, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + }, + MathExpr::Root { + index, + body, + radical, + math_fonts, + } => MathExpr::Root { + index: index.as_deref().map(|index| { + Box::new(transform( + index, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )) + }), + body: Box::new(transform( + body, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + radical: *radical, + math_fonts: math_fonts.clone(), + }, + MathExpr::Delimited { + left, + body, + right, + left_settings, + right_settings, + } => MathExpr::Delimited { + left: left.clone(), + body: Box::new(transform( + body, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + right: right.clone(), + left_settings: *left_settings, + right_settings: *right_settings, + }, + MathExpr::Fenced { + delimiters, + delimiter_settings, + segments, + } => MathExpr::Fenced { + delimiters: delimiters.clone(), + delimiter_settings: delimiter_settings.clone(), + segments: segments + .iter() + .map(|segment| { + transform( + segment, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + ) + }) + .collect(), + }, + MathExpr::Script { + base, + sub, + superscript, + limits, + } => MathExpr::Script { + base: Box::new(transform( + base, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )), + sub: sub.as_deref().map(|sub| { + Box::new(transform( + sub, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )) + }), + superscript: superscript.as_deref().map(|superscript| { + Box::new(transform( + superscript, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + )) + }), + limits: *limits, + }, + MathExpr::Atom { + class: MathClass::Ordinary, + text, + math_family, + math_slots, + math_fonts, + } => transform_atom( + expression, + text, + *math_family, + math_slots, + math_fonts, + alphabet, + bold, + italic, + math_style, + has_selected_font_glyph, + has_default_math_glyph, + ), + MathExpr::Text(_) + | MathExpr::TextStyled { .. } + | MathExpr::Atom { .. } + | MathExpr::MathSpacingChange(_) + | MathExpr::MathLineBreakPenaltiesChange(_) + | MathExpr::BreakPenalty(_) + | MathExpr::MathStyleChange(_) + | MathExpr::Space(_) + | MathExpr::Glue(_) + | MathExpr::Kern(_) + | MathExpr::SizedDelimiter { .. } + | MathExpr::UnicodeDelimiter { .. } => expression.clone(), + } + } + + transform( + expression, + alphabet, + bold, + italic, + math_style, + &has_selected_font_glyph, + &has_default_math_glyph, + ) +} + +fn transform_atom( + original: &MathExpr, + text: &str, + math_family: Option, + math_slots: &[u8], + math_fonts: &MathFontFamilies, + alphabet: MathAlphabet, + bold: bool, + italic: bool, + math_style: MathStyle, + has_selected_font_glyph: &impl Fn(&Path, char) -> bool, + has_default_math_glyph: &impl Fn(char) -> bool, +) -> MathExpr { + let glyph_text = crate::math_glyph::math_atom_glyph_text(text, math_family, math_slots); + let characters = glyph_text.chars().collect::>(); + let has_aligned_slots = math_family.is_some() && math_slots.len() == characters.len(); + let selected_font = math_family + .and_then(|family| math_fonts.get(&family)) + .and_then(|selection| selection.for_style(math_style)); + let mut transformed = false; + let mut items = Vec::with_capacity(characters.len()); + for (index, character) in characters.into_iter().enumerate() { + let alphabet_character = self::character(character, alphabet); + let mapped = alphabet_character.and_then(|mapped| { + if selected_font.is_some_and(|path| has_selected_font_glyph(path.as_path(), mapped)) { + Some((mapped, true)) + } else if has_default_math_glyph(mapped) { + Some((mapped, false)) + } else { + None + } + }); + if let Some((mapped, use_selected_font)) = mapped { + transformed = true; + items.push(MathExpr::Atom { + class: MathClass::Ordinary, + text: mapped.to_string(), + math_family: use_selected_font.then_some(math_family).flatten(), + math_slots: Vec::new(), + math_fonts: math_fonts.clone(), + }); + } else if alphabet_character.is_some() { + transformed = true; + items.push(MathExpr::TextStyled { + text: character.to_string(), + bold, + italic, + monospace: false, + }); + } else { + items.push(MathExpr::Atom { + class: MathClass::Ordinary, + text: character.to_string(), + math_family, + math_slots: if has_aligned_slots { + vec![math_slots[index]] + } else { + Vec::new() + }, + math_fonts: math_fonts.clone(), + }); + } + } + if !transformed { + return original.clone(); + } + match items.len() { + 0 => MathExpr::Sequence(Vec::new()), + 1 => items.pop().expect("one alphabet atom was built"), + _ => MathExpr::Sequence(items), + } +} + +/// Maps a TeX math letter or supported Greek symbol to its Unicode alphabet form. +pub fn character(character: char, alphabet: MathAlphabet) -> Option { + let codepoint = match character { + 'A'..='Z' => { + let offset = u32::from(character) - u32::from('A'); + match alphabet { + MathAlphabet::Bold => 0x1D400 + offset, + MathAlphabet::BoldItalic => 0x1D468 + offset, + MathAlphabet::Italic => 0x1D434 + offset, + MathAlphabet::Script => match character { + 'B' => 0x212C, + 'E' => 0x2130, + 'F' => 0x2131, + 'H' => 0x210B, + 'I' => 0x2110, + 'L' => 0x2112, + 'M' => 0x2133, + 'R' => 0x211B, + _ => 0x1D49C + offset, + }, + MathAlphabet::BoldScript => 0x1D4D0 + offset, + MathAlphabet::Fraktur => match character { + 'C' => 0x212D, + 'H' => 0x210C, + 'I' => 0x2111, + 'R' => 0x211C, + _ => 0x1D504 + offset, + }, + MathAlphabet::BoldFraktur => 0x1D56C + offset, + MathAlphabet::DoubleStruck => match character { + 'C' => 0x2102, + 'H' => 0x210D, + 'N' => 0x2115, + 'P' => 0x2119, + 'Q' => 0x211A, + 'R' => 0x211D, + 'Z' => 0x2124, + _ => 0x1D538 + offset, + }, + MathAlphabet::SansSerif => 0x1D5A0 + offset, + MathAlphabet::SansSerifBold => 0x1D5D4 + offset, + MathAlphabet::SansSerifItalic => 0x1D608 + offset, + MathAlphabet::SansSerifBoldItalic => 0x1D63C + offset, + } + } + 'a'..='z' => { + let offset = u32::from(character) - u32::from('a'); + match alphabet { + MathAlphabet::Bold => 0x1D41A + offset, + MathAlphabet::BoldItalic => 0x1D482 + offset, + MathAlphabet::Italic if character == 'h' => 0x210E, + MathAlphabet::Italic => 0x1D44E + offset, + MathAlphabet::Script => match character { + 'e' => 0x212F, + 'g' => 0x210A, + 'l' => 0x2113, + 'o' => 0x2134, + _ => 0x1D4B6 + offset, + }, + MathAlphabet::BoldScript => 0x1D4EA + offset, + MathAlphabet::Fraktur => 0x1D51E + offset, + MathAlphabet::BoldFraktur => 0x1D586 + offset, + MathAlphabet::DoubleStruck => 0x1D552 + offset, + MathAlphabet::SansSerif => 0x1D5BA + offset, + MathAlphabet::SansSerifBold => 0x1D5EE + offset, + MathAlphabet::SansSerifItalic => 0x1D622 + offset, + MathAlphabet::SansSerifBoldItalic => 0x1D656 + offset, + } + } + '0'..='9' => { + let offset = u32::from(character) - u32::from('0'); + match alphabet { + MathAlphabet::Bold => 0x1D7CE + offset, + MathAlphabet::DoubleStruck => 0x1D7D8 + offset, + MathAlphabet::SansSerif => 0x1D7E2 + offset, + MathAlphabet::SansSerifBold => 0x1D7EC + offset, + _ => return None, + } + } + _ => return greek_math_alphabet_character(character, alphabet), + }; + char::from_u32(codepoint) +} + +fn greek_math_alphabet_character(character: char, alphabet: MathAlphabet) -> Option { + let style_base = match alphabet { + MathAlphabet::Bold => 0x1D6A8, + MathAlphabet::Italic => 0x1D6E2, + MathAlphabet::BoldItalic => 0x1D71C, + MathAlphabet::SansSerifBold => 0x1D756, + MathAlphabet::SansSerifBoldItalic => 0x1D790, + MathAlphabet::BoldScript + | MathAlphabet::BoldFraktur + | MathAlphabet::Script + | MathAlphabet::Fraktur + | MathAlphabet::DoubleStruck + | MathAlphabet::SansSerif + | MathAlphabet::SansSerifItalic => return None, + }; + + let offset = match character as u32 { + 0x0391..=0x03A1 => character as u32 - 0x0391, + 0x03A3..=0x03A9 => character as u32 - 0x03A3 + 18, + 0x03F4 => 17, + 0x2207 => 25, + 0x03B1..=0x03C1 => 26 + character as u32 - 0x03B1, + 0x03C2 => 43, + 0x03C3..=0x03C9 => 44 + character as u32 - 0x03C3, + 0x2202 => 51, + 0x03F5 => 52, + 0x03D1 => 53, + 0x03F0 => 54, + 0x03D5 => 55, + 0x03F1 => 56, + 0x03D6 => 57, + _ => return None, + }; + char::from_u32(style_base + offset) +} diff --git a/crates/texrra-core/src/math_code.rs b/crates/texrra-core/src/math_code.rs new file mode 100644 index 0000000..d4a2e21 --- /dev/null +++ b/crates/texrra-core/src/math_code.rs @@ -0,0 +1,276 @@ +use std::collections::HashMap; + +use crate::{MathClass, MathCode}; + +static DEFAULT_MATH_CODE: MathCode = MathCode(0); +static UNSET_UNICODE_MATH_CODE: i32 = -1; +static UNSET_DELIMITER_CODE: i32 = -1; + +/// Character math codes owned by the Rust TeX engine. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct MathCodeTable { + low: Vec, + high: HashMap, + groups: Vec, +} + +#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] +struct MathCodeGroup { + values: HashMap>, +} + +impl MathCodeTable { + pub fn get_index_ref(&self, index: usize) -> &MathCode { + self.low + .get(index) + .or_else(|| self.high.get(&index)) + .unwrap_or(&DEFAULT_MATH_CODE) + } + + pub fn get_index_mut_ref(&mut self, index: usize) -> &mut MathCode { + if let Some(math_code) = self.low.get_mut(index) { + return math_code; + } + self.high.entry(index).or_default() + } + + pub fn prepare_assignment(&mut self, index: usize, global: bool) { + if global { + for group in &mut self.groups { + group.values.remove(&index); + } + } else if !self.groups.is_empty() { + let previous = self.stored_value(index); + self.groups + .last_mut() + .expect("math code group exists") + .values + .entry(index) + .or_insert(previous); + } + } + + pub fn begin_group(&mut self) { + self.groups.push(MathCodeGroup::default()); + } + + pub fn end_group(&mut self) { + let Some(group) = self.groups.pop() else { + return; + }; + for (index, value) in group.values { + self.set_index(index, value); + } + } + + fn stored_value(&self, index: usize) -> Option { + self.low + .get(index) + .copied() + .or_else(|| self.high.get(&index).copied()) + } + + fn set_index(&mut self, index: usize, value: Option) { + if let Some(math_code) = self.low.get_mut(index) { + if let Some(value) = value { + *math_code = value; + } + return; + } + match value { + Some(math_code) => { + self.high.insert(index, math_code); + } + None => { + self.high.remove(&index); + } + } + } +} + +impl Default for MathCodeTable { + fn default() -> Self { + Self { + low: vec![MathCode::default(); 128], + high: HashMap::new(), + groups: Vec::new(), + } + } +} + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub struct UnicodeMathCode { + pub class: u8, + pub family: u8, + pub glyph_slot: u32, +} + +impl UnicodeMathCode { + pub fn pack(self) -> u32 { + (u32::from(self.family) << 24) | (u32::from(self.class) << 21) | self.glyph_slot + } + + pub fn unpack(code: u32) -> Self { + Self { + class: ((code >> 21) & 0x7) as u8, + family: (code >> 24) as u8, + glyph_slot: code & 0x1F_FFFF, + } + } + + pub fn character(self) -> char { + char::from_u32(self.glyph_slot) + .expect("Unicode math glyph slots contain valid scalar values") + } + + pub fn math_class(self) -> MathClass { + match self.class { + 0 | 7 => MathClass::Ordinary, + 1 => MathClass::Operator, + 2 => MathClass::Binary, + 3 => MathClass::Relation, + 4 => MathClass::Opening, + 5 => MathClass::Closing, + 6 => MathClass::Punctuation, + _ => unreachable!("math character classes use three bits"), + } + } + + pub fn math_family(self, active_family: Option) -> u8 { + if self.class == 7 { + active_family + .filter(|family| (0..=255).contains(family)) + .map(|family| family as u8) + .unwrap_or(self.family) + } else { + self.family + } + } +} + +#[derive(Default, serde::Serialize, serde::Deserialize)] +pub struct UnicodeMathCodeTable { + values: HashMap, + groups: Vec, +} + +#[derive(Default, serde::Serialize, serde::Deserialize)] +struct UnicodeMathCodeGroup { + values: HashMap>, +} + +impl UnicodeMathCodeTable { + pub fn get(&self, codepoint: usize) -> Option { + let value = self.values.get(&codepoint).copied()?; + (value != UNSET_UNICODE_MATH_CODE).then(|| UnicodeMathCode::unpack(value as u32)) + } + + pub fn get_index_ref(&self, codepoint: usize) -> &i32 { + self.values + .get(&codepoint) + .unwrap_or(&UNSET_UNICODE_MATH_CODE) + } + + pub fn get_index_mut_ref(&mut self, codepoint: usize) -> &mut i32 { + self.values + .entry(codepoint) + .or_insert(UNSET_UNICODE_MATH_CODE) + } + + pub fn prepare_assignment(&mut self, codepoint: usize, global: bool) { + if global { + for group in &mut self.groups { + group.values.remove(&codepoint); + } + } else if !self.groups.is_empty() { + let previous = self.values.get(&codepoint).copied(); + self.groups + .last_mut() + .expect("Unicode math code group exists") + .values + .entry(codepoint) + .or_insert(previous); + } + } + + pub fn begin_group(&mut self) { + self.groups.push(UnicodeMathCodeGroup::default()); + } + + pub fn end_group(&mut self) { + let Some(group) = self.groups.pop() else { + return; + }; + for (codepoint, value) in group.values { + match value { + Some(value) => { + self.values.insert(codepoint, value); + } + None => { + self.values.remove(&codepoint); + } + } + } + } +} + +#[derive(Default, serde::Serialize, serde::Deserialize)] +pub struct DelimiterCodeTable { + values: HashMap, + groups: Vec, +} + +#[derive(Default, serde::Serialize, serde::Deserialize)] +struct DelimiterCodeGroup { + values: HashMap>, +} + +impl DelimiterCodeTable { + pub fn get_index_ref(&self, codepoint: usize) -> &i32 { + self.values.get(&codepoint).unwrap_or(&UNSET_DELIMITER_CODE) + } + + pub fn get_index_mut_ref(&mut self, codepoint: usize) -> &mut i32 { + self.values.entry(codepoint).or_insert(UNSET_DELIMITER_CODE) + } + + pub fn prepare_assignment(&mut self, codepoint: usize, global: bool) { + if global { + for group in &mut self.groups { + group.values.remove(&codepoint); + } + } else if !self.groups.is_empty() { + let previous = self.values.get(&codepoint).copied(); + self.groups + .last_mut() + .expect("delimiter code group exists") + .values + .entry(codepoint) + .or_insert(previous); + } + } + + pub fn begin_group(&mut self) { + self.groups.push(DelimiterCodeGroup::default()); + } + + pub fn end_group(&mut self) { + let Some(group) = self.groups.pop() else { + return; + }; + for (codepoint, value) in group.values { + match value { + Some(value) => { + self.values.insert(codepoint, value); + } + None => { + self.values.remove(&codepoint); + } + } + } + } + + pub fn assign(&mut self, codepoint: usize, value: i32) { + self.values.insert(codepoint, value); + } +} diff --git a/crates/texrra-core/src/math_constants.rs b/crates/texrra-core/src/math_constants.rs new file mode 100644 index 0000000..9ff4e82 --- /dev/null +++ b/crates/texrra-core/src/math_constants.rs @@ -0,0 +1,411 @@ +/// OpenType MATH constants, retained in the font's design units. +#[derive(Clone, Copy, Debug)] +pub struct MathConstants { + pub script_percent_scale_down: i16, + pub script_script_percent_scale_down: i16, + pub display_operator_min_height: u16, + pub axis_height: i16, + pub accent_base_height: i16, + pub subscript_top_max: i16, + pub subscript_baseline_drop_min: i16, + pub subscript_shift_down: i16, + pub superscript_bottom_min: i16, + pub superscript_baseline_drop_max: i16, + pub superscript_bottom_max_with_subscript: i16, + pub superscript_shift_up: i16, + pub superscript_shift_up_cramped: i16, + pub sub_superscript_gap_min: i16, + pub upper_limit_gap_min: i16, + pub upper_limit_baseline_rise_min: i16, + pub lower_limit_gap_min: i16, + pub lower_limit_baseline_drop_min: i16, + pub space_after_script: i16, + pub stack_top_shift_up: i16, + pub stack_bottom_shift_down: i16, + pub stack_gap_min: i16, + pub stack_display_style_gap_min: i16, + pub fraction_numerator_shift_up: i16, + pub fraction_numerator_display_style_shift_up: i16, + pub fraction_denominator_shift_down: i16, + pub fraction_denominator_display_style_shift_down: i16, + pub fraction_numerator_gap_min: i16, + pub fraction_num_display_style_gap_min: i16, + pub fraction_rule_thickness: i16, + pub fraction_denominator_gap_min: i16, + pub fraction_denom_display_style_gap_min: i16, + pub overbar_vertical_gap: i16, + pub overbar_rule_thickness: i16, + pub overbar_extra_ascender: i16, + pub underbar_vertical_gap: i16, + pub underbar_rule_thickness: i16, + pub underbar_extra_descender: i16, + pub radical_vertical_gap: i16, + pub radical_display_style_vertical_gap: i16, + pub radical_rule_thickness: i16, + pub radical_kern_before_degree: i16, + pub radical_kern_after_degree: i16, + pub radical_degree_bottom_raise_percent: i16, +} + +/// TeX fraction parameters expressed as fractions of the math font's em. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathFractionParameters { + pub numerator_shift_up: f64, + pub denominator_shift_down: f64, + pub numerator_gap_min: f64, + pub denominator_gap_min: f64, + pub rule_thickness: f64, + pub stack_gap_min: f64, + pub axis_height: f64, +} + +/// TeX script parameters expressed as fractions of the math font's em. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathScriptParameters { + pub subscript_top_max: f64, + pub subscript_baseline_drop_min: f64, + pub subscript_shift_down: f64, + pub superscript_bottom_min: f64, + pub superscript_baseline_drop_max: f64, + pub superscript_bottom_max_with_subscript: f64, + pub superscript_shift_up: f64, + pub superscript_shift_up_cramped: f64, + pub sub_superscript_gap_min: f64, + pub space_after_script: f64, +} + +/// TeX operator-limit parameters expressed as fractions of the math font's em. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathLimitParameters { + pub upper_gap_min: f64, + pub upper_baseline_rise_min: f64, + pub lower_gap_min: f64, + pub lower_baseline_drop_min: f64, + pub outer_padding: f64, +} + +/// OpenType MATH and XeTeX fallback values for a radical, expressed in ems. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathRadicalParameters { + pub clearance: f64, + pub rule_thickness: f64, + pub extra_ascender: f64, +} + +/// Radical-index placement parameters, with lengths expressed in ems. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathRadicalDegreeParameters { + pub kern_before_degree: f64, + pub kern_after_degree: f64, + pub bottom_raise_percent: f64, +} + +/// Overbar or underbar parameters, expressed as em fractions. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathBarParameters { + pub vertical_gap: f64, + pub rule_thickness: f64, + pub extra_extent: f64, +} + +/// Selects the OpenType MATH or TeX fallback values for a fraction. +pub fn fraction_parameters( + constants: Option, + units_per_em: f64, + display_style: bool, + has_rule: bool, +) -> MathFractionParameters { + let numerator_shift_up = constants.map(|constants| { + if display_style { + constants.fraction_numerator_display_style_shift_up + } else if has_rule { + constants.fraction_numerator_shift_up + } else { + constants.stack_top_shift_up + } + }); + let denominator_shift_down = constants.map(|constants| { + if display_style { + constants.fraction_denominator_display_style_shift_down + } else if has_rule { + constants.fraction_denominator_shift_down + } else { + constants.stack_bottom_shift_down + } + }); + let (numerator_gap_min, denominator_gap_min) = constants + .map(|constants| { + if display_style { + ( + Some(constants.fraction_num_display_style_gap_min), + Some(constants.fraction_denom_display_style_gap_min), + ) + } else { + ( + Some(constants.fraction_numerator_gap_min), + Some(constants.fraction_denominator_gap_min), + ) + } + }) + .unwrap_or((None, None)); + let rule_thickness = signed_em( + constants.map(|constants| constants.fraction_rule_thickness), + units_per_em, + 0.04, + ); + let numerator_gap_min = signed_em(numerator_gap_min, units_per_em, 0.0); + let denominator_gap_min = signed_em(denominator_gap_min, units_per_em, 0.0); + let numerator_gap_min = if constants.is_some() { + numerator_gap_min + } else { + rule_thickness * if display_style { 3.0 } else { 1.0 } + }; + let denominator_gap_min = if constants.is_some() { + denominator_gap_min + } else { + rule_thickness * if display_style { 3.0 } else { 1.0 } + }; + let stack_gap_min = constants + .map(|constants| { + if display_style { + constants.stack_display_style_gap_min + } else { + constants.stack_gap_min + } + }) + .map(|gap| signed_em(Some(gap), units_per_em, 0.0)) + .unwrap_or(rule_thickness * if display_style { 7.0 } else { 3.0 }); + + MathFractionParameters { + numerator_shift_up: signed_em(numerator_shift_up, units_per_em, 0.0), + denominator_shift_down: signed_em(denominator_shift_down, units_per_em, 0.0), + numerator_gap_min, + denominator_gap_min, + rule_thickness, + stack_gap_min, + axis_height: signed_em( + constants.map(|constants| constants.axis_height), + units_per_em, + 0.25, + ), + } +} + +/// Selects the OpenType MATH or TeX fallback values for scripts. +pub fn script_parameters( + constants: Option, + units_per_em: f64, +) -> MathScriptParameters { + let value = |select: fn(MathConstants) -> i16, fallback| { + signed_em(constants.map(select), units_per_em, fallback) + }; + MathScriptParameters { + subscript_top_max: value(|c| c.subscript_top_max, 0.36), + subscript_baseline_drop_min: value(|c| c.subscript_baseline_drop_min, 0.0), + subscript_shift_down: value(|c| c.subscript_shift_down, 0.2), + superscript_bottom_min: value(|c| c.superscript_bottom_min, 0.1125), + superscript_baseline_drop_max: value(|c| c.superscript_baseline_drop_max, 0.0), + superscript_bottom_max_with_subscript: value( + |c| c.superscript_bottom_max_with_subscript, + 0.36, + ), + superscript_shift_up: value(|c| c.superscript_shift_up, 0.35), + superscript_shift_up_cramped: value(|c| c.superscript_shift_up_cramped, 0.35), + sub_superscript_gap_min: value(|c| c.sub_superscript_gap_min, 0.15), + space_after_script: value(|c| c.space_after_script, 0.0), + } +} + +/// Selects the OpenType MATH or XeTeX fallback values for operator limits. +pub fn limit_parameters( + constants: Option, + units_per_em: f64, +) -> MathLimitParameters { + let value = |select: fn(MathConstants) -> i16, fallback| { + signed_em(constants.map(select), units_per_em, fallback) + }; + MathLimitParameters { + upper_gap_min: value(|c| c.upper_limit_gap_min, 0.05), + upper_baseline_rise_min: value(|c| c.upper_limit_baseline_rise_min, 0.3), + lower_gap_min: value(|c| c.lower_limit_gap_min, 0.05), + lower_baseline_drop_min: value(|c| c.lower_limit_baseline_drop_min, 0.3), + // XeTeX maps BigOpSpacing5 to StackGapMin for OpenType MATH fonts. + outer_padding: value(|c| c.stack_gap_min, 0.1), + } +} + +/// Selects the OpenType MATH or XeTeX fallback values for a radical. +pub fn radical_parameters( + constants: Option, + units_per_em: f64, + display_style: bool, + x_height: Option, +) -> MathRadicalParameters { + let rule_thickness = signed_em( + constants.map(|constants| constants.radical_rule_thickness), + units_per_em, + 0.04, + ); + let clearance = match constants { + Some(constants) => signed_em( + Some(if display_style { + constants.radical_display_style_vertical_gap + } else { + constants.radical_vertical_gap + }), + units_per_em, + 0.0, + ), + None if display_style => rule_thickness + signed_em(x_height, units_per_em, 0.45) / 4.0, + None => rule_thickness + rule_thickness / 4.0, + }; + MathRadicalParameters { + clearance, + rule_thickness, + // XeTeX starts the radical overbar with a kern equal to rule thickness. + extra_ascender: rule_thickness, + } +} + +/// Selects the OpenType MATH or XeTeX fallback values for a radical index. +pub fn radical_degree_parameters( + constants: Option, + units_per_em: f64, +) -> MathRadicalDegreeParameters { + let kern_before_degree = signed_em( + constants.map(|constants| constants.radical_kern_before_degree), + units_per_em, + 5.0 / 18.0, + ); + let kern_after_degree = signed_em( + constants.map(|constants| constants.radical_kern_after_degree), + units_per_em, + -10.0 / 18.0, + ); + let bottom_raise_percent = constants + .map(|constants| constants.radical_degree_bottom_raise_percent) + .unwrap_or(60) + .clamp(0, 100); + MathRadicalDegreeParameters { + kern_before_degree, + kern_after_degree, + bottom_raise_percent: f64::from(bottom_raise_percent) / 100.0, + } +} + +/// Selects OpenType MATH or XeTeX fallback parameters for an overbar. +pub fn overbar_parameters( + constants: Option, + units_per_em: f64, +) -> MathBarParameters { + MathBarParameters { + vertical_gap: signed_em( + constants.map(|constants| constants.overbar_vertical_gap), + units_per_em, + 0.1, + ), + rule_thickness: signed_em( + constants.map(|constants| constants.overbar_rule_thickness), + units_per_em, + 0.04, + ), + extra_extent: signed_em( + constants.map(|constants| constants.overbar_extra_ascender), + units_per_em, + 0.0, + ), + } +} + +/// Selects OpenType MATH or XeTeX fallback parameters for an underbar. +pub fn underbar_parameters( + constants: Option, + units_per_em: f64, +) -> MathBarParameters { + MathBarParameters { + vertical_gap: signed_em( + constants.map(|constants| constants.underbar_vertical_gap), + units_per_em, + 0.1, + ), + rule_thickness: signed_em( + constants.map(|constants| constants.underbar_rule_thickness), + units_per_em, + 0.04, + ), + extra_extent: signed_em( + constants.map(|constants| constants.underbar_extra_descender), + units_per_em, + 0.0, + ), + } +} + +fn signed_em(value: Option, units_per_em: f64, fallback_em: f64) -> f64 { + value + .map(|value| f64::from(value) / units_per_em) + .unwrap_or(fallback_em) +} + +impl MathConstants { + pub fn from_ttf(constants: ttf_parser::math::Constants<'_>) -> Self { + Self { + script_percent_scale_down: constants.script_percent_scale_down(), + script_script_percent_scale_down: constants.script_script_percent_scale_down(), + display_operator_min_height: constants.display_operator_min_height(), + axis_height: constants.axis_height().value, + accent_base_height: constants.accent_base_height().value, + subscript_top_max: constants.subscript_top_max().value, + subscript_baseline_drop_min: constants.subscript_baseline_drop_min().value, + subscript_shift_down: constants.subscript_shift_down().value, + superscript_bottom_min: constants.superscript_bottom_min().value, + superscript_baseline_drop_max: constants.superscript_baseline_drop_max().value, + superscript_bottom_max_with_subscript: constants + .superscript_bottom_max_with_subscript() + .value, + superscript_shift_up: constants.superscript_shift_up().value, + superscript_shift_up_cramped: constants.superscript_shift_up_cramped().value, + sub_superscript_gap_min: constants.sub_superscript_gap_min().value, + upper_limit_gap_min: constants.upper_limit_gap_min().value, + upper_limit_baseline_rise_min: constants.upper_limit_baseline_rise_min().value, + lower_limit_gap_min: constants.lower_limit_gap_min().value, + lower_limit_baseline_drop_min: constants.lower_limit_baseline_drop_min().value, + space_after_script: constants.space_after_script().value, + stack_top_shift_up: constants.stack_top_shift_up().value, + stack_bottom_shift_down: constants.stack_bottom_shift_down().value, + stack_gap_min: constants.stack_gap_min().value, + stack_display_style_gap_min: constants.stack_display_style_gap_min().value, + fraction_numerator_shift_up: constants.fraction_numerator_shift_up().value, + fraction_numerator_display_style_shift_up: constants + .fraction_numerator_display_style_shift_up() + .value, + fraction_denominator_shift_down: constants.fraction_denominator_shift_down().value, + fraction_denominator_display_style_shift_down: constants + .fraction_denominator_display_style_shift_down() + .value, + fraction_numerator_gap_min: constants.fraction_numerator_gap_min().value, + fraction_num_display_style_gap_min: constants + .fraction_num_display_style_gap_min() + .value, + fraction_rule_thickness: constants.fraction_rule_thickness().value, + fraction_denominator_gap_min: constants.fraction_denominator_gap_min().value, + fraction_denom_display_style_gap_min: constants + .fraction_denom_display_style_gap_min() + .value, + overbar_vertical_gap: constants.overbar_vertical_gap().value, + overbar_rule_thickness: constants.overbar_rule_thickness().value, + overbar_extra_ascender: constants.overbar_extra_ascender().value, + underbar_vertical_gap: constants.underbar_vertical_gap().value, + underbar_rule_thickness: constants.underbar_rule_thickness().value, + underbar_extra_descender: constants.underbar_extra_descender().value, + radical_vertical_gap: constants.radical_vertical_gap().value, + radical_display_style_vertical_gap: constants + .radical_display_style_vertical_gap() + .value, + radical_rule_thickness: constants.radical_rule_thickness().value, + radical_kern_before_degree: constants.radical_kern_before_degree().value, + radical_kern_after_degree: constants.radical_kern_after_degree().value, + radical_degree_bottom_raise_percent: constants.radical_degree_bottom_raise_percent(), + } + } +} diff --git a/crates/texrra-core/src/math_expr.rs b/crates/texrra-core/src/math_expr.rs new file mode 100644 index 0000000..a8943f4 --- /dev/null +++ b/crates/texrra-core/src/math_expr.rs @@ -0,0 +1,1424 @@ +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + hash::{Hash, Hasher}, + path::PathBuf, + sync::Arc, +}; + +use crate::{MathClass, MathStyle, MathStyleCommand, TeXGlue, source::SourceLocation}; + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum MathExpr { + Text(String), + TextStyled { + text: String, + bold: bool, + italic: bool, + monospace: bool, + }, + Spanned { + location: Option, + expression: Box, + }, + Styled { + font: MathFontStyle, + expression: Box, + }, + Classified { + class: MathClass, + body: Box, + }, + Phantom { + kind: MathPhantomKind, + body: Box, + }, + Accent { + position: MathAccent, + body: Box, + family: u8, + math_fonts: MathFontFamilies, + }, + Atom { + class: MathClass, + text: String, + math_family: Option, + math_slots: Vec, + math_fonts: MathFontFamilies, + }, + MathSpacingChange(MathSpacingSettings), + MathLineBreakPenaltiesChange(MathLineBreakPenalties), + BreakPenalty(i32), + MathStyleChange(MathStyleCommand), + Space(i8), + Glue(TeXGlue), + Kern(common::Scaled), + Sequence(Vec), + Alignment { + rows: Vec>, + alignment: MathAlignment, + baseline: MathAlignmentBaseline, + math_fonts: MathFontFamilies, + cell_style: MathCellStyle, + row_spacing: MathRowSpacing, + }, + Fraction { + numerator: Box, + denominator: Box, + style: MathFractionStyle, + has_rule: bool, + rule_thickness: Option, + math_fonts: MathFontFamilies, + }, + MathChoice { + display: Box, + text: Box, + script: Box, + scriptscript: Box, + }, + Root { + index: Option>, + body: Box, + radical: Option<(u8, char)>, + math_fonts: MathFontFamilies, + }, + Delimited { + left: MathDelimiterGlyph, + body: Box, + right: MathDelimiterGlyph, + left_settings: MathDelimiterSettings, + right_settings: MathDelimiterSettings, + }, + SizedDelimiter { + delimiter: String, + half_points: u8, + class: MathClass, + settings: MathDelimiterSettings, + math_fonts: MathFontFamilies, + }, + UnicodeDelimiter { + character: char, + class: MathClass, + family: u8, + settings: MathDelimiterSettings, + math_fonts: MathFontFamilies, + }, + Fenced { + delimiters: Vec, + delimiter_settings: Vec, + segments: Vec, + }, + Script { + base: Box, + sub: Option>, + superscript: Option>, + limits: MathLimitMode, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct MathMuGlue(pub common::Glue); + +impl Hash for MathMuGlue { + fn hash(&self, state: &mut H) { + self.0.width.hash(state); + self.0.stretch.hash(state); + (self.0.stretch_order as u8).hash(state); + self.0.shrink.hash(state); + (self.0.shrink_order as u8).hash(state); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct MathLineBreakPenalties { + pub binary: i32, + pub relation: i32, +} + +impl Default for MathLineBreakPenalties { + fn default() -> Self { + Self { + binary: 700, + relation: 500, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct MathSpacingSettings { + pub thin: MathMuGlue, + pub medium: MathMuGlue, + pub thick: MathMuGlue, +} + +impl Default for MathSpacingSettings { + fn default() -> Self { + let glue = |width, stretch, shrink| { + MathMuGlue(common::Glue { + width: common::Scaled::ONE * width, + stretch: common::Scaled::ONE * stretch, + shrink: common::Scaled::ONE * shrink, + ..common::Glue::default() + }) + }; + Self { + thin: glue(3, 0, 0), + medium: glue(4, 2, 4), + thick: glue(5, 5, 0), + } + } +} + +/// Font files assigned to one math family at each TeX math style size. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct MathFontSelection { + pub text: Option, + pub script: Option, + pub scriptscript: Option, +} + +pub type MathFontFamilies = Arc>; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct MathDelimiterCharacter { + pub family: u8, + pub character: char, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct MathDelimiterGlyph { + pub text: String, + pub small: Option, + pub large: Option, + pub is_null: bool, + pub math_fonts: MathFontFamilies, +} + +impl MathDelimiterGlyph { + pub fn plain(text: impl Into) -> Self { + Self::plain_with_math_fonts(text, Arc::default()) + } + + pub fn plain_with_math_fonts(text: impl Into, math_fonts: MathFontFamilies) -> Self { + Self { + text: text.into(), + small: None, + large: None, + is_null: false, + math_fonts, + } + } + + pub fn collect_math_font_files(&self, files: &mut HashSet) { + for family in [self.small, self.large].into_iter().flatten() { + if let Some(selection) = self.math_fonts.get(&family.family) { + selection.collect_files(files); + } + } + if let Some(selection) = self.math_fonts.get(&2) { + selection.collect_files(files); + } + } +} + +impl MathFontSelection { + fn collect_files(&self, files: &mut HashSet) { + files.extend( + [ + self.text.as_ref(), + self.script.as_ref(), + self.scriptscript.as_ref(), + ] + .into_iter() + .flatten() + .cloned(), + ); + } + + pub fn for_style(&self, style: MathStyle) -> Option<&PathBuf> { + match style { + MathStyle::Display + | MathStyle::DisplayCramped + | MathStyle::Text + | MathStyle::TextCramped => self.text.as_ref(), + MathStyle::Script | MathStyle::ScriptCramped => self.script.as_ref(), + MathStyle::ScriptScript | MathStyle::ScriptScriptCramped => self.scriptscript.as_ref(), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum MathAlignment { + Alternating, + AlternatingTight, + Centered, + Left, + Multline, + Columns(Vec), + ArrayColumns { + columns: Vec, + vertical_rules: Vec, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathAlignmentBaseline { + FirstRow, + MathAxisCentered, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathCellStyle { + Inherit, + Display, + Text, + Script, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathRowSpacing { + Array, + Cases, + Equation(common::Scaled), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct MathDelimiterSettings { + pub factor: i32, + pub shortfall: common::Scaled, +} + +impl Default for MathDelimiterSettings { + fn default() -> Self { + Self { + factor: 901, + shortfall: common::Scaled(5 * 65_536), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathFractionStyle { + Automatic, + Display, + Text, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum MathInfixFractionKind { + Over, + Atop, + Choose(MathDelimiterSettings), + Above(common::Scaled), + OverWithDelims(MathFractionDelimiters), + AtopWithDelims(MathFractionDelimiters), + AboveWithDelims { + thickness: common::Scaled, + delimiters: MathFractionDelimiters, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct MathFractionDelimiters { + pub left: MathDelimiterGlyph, + pub right: MathDelimiterGlyph, + pub settings: MathDelimiterSettings, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathPhantomKind { + Both, + Horizontal, + Vertical, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathColumnAlignment { + Left, + Center, + Right, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathFontStyle { + Blackboard, + Bold, + BoldRoman, + Calligraphic, + Fraktur, + Italic, + Monospace, + Roman, + SansSerif, + Text, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathLimitMode { + Automatic, + DisplayLimits, + Limits, + NoLimits, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathAccent { + Overline, + Underline, + Hat, + Tilde, + WideHat, + WideTilde, + OverBrace, + UnderBrace, + Unicode { + class: MathClass, + family: u8, + character: char, + stretch: bool, + bottom: bool, + }, +} + +fn math_accent_class(accent: MathAccent) -> MathClass { + match accent { + MathAccent::Unicode { class, .. } => class, + _ => MathClass::Ordinary, + } +} + +impl MathExpr { + pub fn collect_math_font_files(&self, files: &mut HashSet) { + match self { + Self::Atom { + math_family, + math_fonts, + .. + } => { + if let Some(selection) = math_family.and_then(|family| math_fonts.get(&family)) { + files.extend( + [ + selection.text.as_ref(), + selection.script.as_ref(), + selection.scriptscript.as_ref(), + ] + .into_iter() + .flatten() + .cloned(), + ); + } + } + Self::Spanned { expression, .. } | Self::Styled { expression, .. } => { + expression.collect_math_font_files(files) + } + Self::Classified { body, .. } | Self::Phantom { body, .. } => { + body.collect_math_font_files(files) + } + Self::Accent { + position, + body, + family, + math_fonts, + } => { + if !matches!(position, MathAccent::Overline | MathAccent::Underline) { + if let Some(selection) = math_fonts.get(family) { + files.extend( + [ + selection.text.as_ref(), + selection.script.as_ref(), + selection.scriptscript.as_ref(), + ] + .into_iter() + .flatten() + .cloned(), + ); + } + } + body.collect_math_font_files(files); + } + Self::Sequence(items) => { + for item in items { + item.collect_math_font_files(files); + } + } + Self::Alignment { + rows, math_fonts, .. + } => { + if let Some(selection) = math_fonts.get(&2) { + selection.collect_files(files); + } + for item in rows.iter().flatten() { + item.collect_math_font_files(files); + } + } + Self::Fraction { + numerator, + denominator, + math_fonts, + .. + } => { + if let Some(selection) = math_fonts.get(&2) { + selection.collect_files(files); + } + numerator.collect_math_font_files(files); + denominator.collect_math_font_files(files); + } + Self::MathChoice { + display, + text, + script, + scriptscript, + } => { + display.collect_math_font_files(files); + text.collect_math_font_files(files); + script.collect_math_font_files(files); + scriptscript.collect_math_font_files(files); + } + Self::Root { + index, + body, + radical, + math_fonts, + } => { + if let Some((family, _)) = radical { + if let Some(selection) = math_fonts.get(family) { + files.extend( + [ + selection.text.as_ref(), + selection.script.as_ref(), + selection.scriptscript.as_ref(), + ] + .into_iter() + .flatten() + .cloned(), + ); + } + } + if let Some(index) = index { + index.collect_math_font_files(files); + } + body.collect_math_font_files(files); + } + Self::UnicodeDelimiter { + family, math_fonts, .. + } => { + if let Some(selection) = math_fonts.get(family) { + selection.collect_files(files); + } + if let Some(selection) = math_fonts.get(&2) { + selection.collect_files(files); + } + } + Self::SizedDelimiter { math_fonts, .. } => { + if let Some(selection) = math_fonts.get(&2) { + selection.collect_files(files); + } + } + Self::Delimited { + left, body, right, .. + } => { + left.collect_math_font_files(files); + right.collect_math_font_files(files); + body.collect_math_font_files(files); + } + Self::Fenced { + delimiters, + segments, + .. + } => { + for delimiter in delimiters { + delimiter.collect_math_font_files(files); + } + for segment in segments { + segment.collect_math_font_files(files); + } + } + Self::Script { + base, + sub, + superscript, + .. + } => { + base.collect_math_font_files(files); + if let Some(sub) = sub { + sub.collect_math_font_files(files); + } + if let Some(superscript) = superscript { + superscript.collect_math_font_files(files); + } + } + Self::Text(_) + | Self::TextStyled { .. } + | Self::MathSpacingChange(_) + | Self::MathLineBreakPenaltiesChange(_) + | Self::BreakPenalty(_) + | Self::MathStyleChange(_) + | Self::Space(_) + | Self::Glue(_) + | Self::Kern(_) => {} + } + } + + pub fn plain_text(&self) -> String { + match self { + Self::Text(text) => text.clone(), + Self::TextStyled { text, .. } => text.clone(), + Self::Spanned { expression, .. } => expression.plain_text(), + Self::Styled { expression, .. } => expression.plain_text(), + Self::Classified { body, .. } | Self::Phantom { body, .. } => body.plain_text(), + Self::Accent { position, body, .. } => { + let mark = match position { + MathAccent::Overline => '\u{0305}', + MathAccent::Underline => '\u{0332}', + MathAccent::Hat => '^', + MathAccent::Tilde => '~', + MathAccent::WideHat => '\u{0302}', + MathAccent::WideTilde => '\u{0303}', + MathAccent::OverBrace => '\u{23de}', + MathAccent::UnderBrace => '\u{23df}', + MathAccent::Unicode { character, .. } => *character, + }; + format!("{}{mark}", body.plain_text()) + } + Self::Atom { text, .. } => text.clone(), + Self::SizedDelimiter { delimiter, .. } => delimiter.clone(), + Self::UnicodeDelimiter { character, .. } => character.to_string(), + Self::MathSpacingChange(_) + | Self::MathLineBreakPenaltiesChange(_) + | Self::BreakPenalty(_) + | Self::MathStyleChange(_) => String::new(), + Self::Space(units) => { + if *units <= 0 { + String::new() + } else { + " ".to_string() + } + } + Self::Kern(_) => String::new(), + Self::Glue(_) => String::new(), + Self::Sequence(items) => items + .iter() + .map(Self::plain_text) + .collect::>() + .join(""), + Self::Alignment { rows, .. } => rows + .iter() + .map(|row| { + row.iter() + .map(Self::plain_text) + .collect::>() + .join(" & ") + }) + .collect::>() + .join("\n"), + Self::Fraction { + numerator, + denominator, + .. + } => { + format!("{}⁄{}", numerator.plain_text(), denominator.plain_text()) + } + Self::MathChoice { display, .. } => display.plain_text(), + Self::Root { + index, + body, + radical, + .. + } => { + let index = index + .as_deref() + .map(|index| format!("[{}]", index.plain_text())) + .unwrap_or_default(); + let radical = radical.map(|(_, character)| character).unwrap_or('√'); + format!("{radical}{index}({})", body.plain_text()) + } + Self::Delimited { + left, body, right, .. + } => { + format!("{}{}{}", left.text, body.plain_text(), right.text) + } + Self::Fenced { + delimiters, + segments, + .. + } => { + let mut text = String::new(); + for (index, segment) in segments.iter().enumerate() { + if let Some(delimiter) = delimiters.get(index) { + text.push_str(&delimiter.text); + } + text.push_str(&segment.plain_text()); + } + if let Some(delimiter) = delimiters.last() { + text.push_str(&delimiter.text); + } + text + } + Self::Script { + base, + sub, + superscript, + .. + } => { + let mut text = base.plain_text(); + if let Some(superscript) = superscript { + text.push_str(&format_script(&superscript.plain_text(), true)); + } + if let Some(sub) = sub { + text.push_str(&format_script(&sub.plain_text(), false)); + } + text + } + } + } + + pub fn contains_cjk(&self) -> bool { + match self { + Self::Text(text) | Self::TextStyled { text, .. } => text.chars().any(is_cjk), + Self::Spanned { expression, .. } => expression.contains_cjk(), + Self::Styled { expression, .. } => expression.contains_cjk(), + Self::Classified { body, .. } | Self::Phantom { body, .. } => body.contains_cjk(), + Self::Accent { body, .. } => body.contains_cjk(), + Self::Atom { text, .. } => text.chars().any(is_cjk), + Self::MathStyleChange(_) + | Self::MathSpacingChange(_) + | Self::MathLineBreakPenaltiesChange(_) + | Self::BreakPenalty(_) + | Self::Space(_) + | Self::Glue(_) + | Self::Kern(_) + | Self::SizedDelimiter { .. } + | Self::UnicodeDelimiter { .. } => false, + Self::Sequence(items) => items.iter().any(Self::contains_cjk), + Self::Alignment { rows, .. } => rows.iter().flatten().any(Self::contains_cjk), + Self::Fraction { + numerator, + denominator, + .. + } => numerator.contains_cjk() || denominator.contains_cjk(), + Self::MathChoice { + display, + text, + script, + scriptscript, + } => { + display.contains_cjk() + || text.contains_cjk() + || script.contains_cjk() + || scriptscript.contains_cjk() + } + Self::Root { index, body, .. } => { + body.contains_cjk() || index.as_deref().is_some_and(Self::contains_cjk) + } + Self::Delimited { body, .. } => body.contains_cjk(), + Self::Fenced { segments, .. } => segments.iter().any(Self::contains_cjk), + Self::Script { + base, + sub, + superscript, + .. + } => { + base.contains_cjk() + || sub.as_deref().is_some_and(Self::contains_cjk) + || superscript.as_deref().is_some_and(Self::contains_cjk) + } + } + } + + pub fn contains_monospace_text(&self) -> bool { + match self { + Self::TextStyled { monospace, .. } => *monospace, + Self::Spanned { expression, .. } | Self::Styled { expression, .. } => { + expression.contains_monospace_text() + } + Self::Classified { body, .. } + | Self::Phantom { body, .. } + | Self::Accent { body, .. } => body.contains_monospace_text(), + Self::Sequence(items) => items.iter().any(Self::contains_monospace_text), + Self::Alignment { rows, .. } => { + rows.iter().flatten().any(Self::contains_monospace_text) + } + Self::Fraction { + numerator, + denominator, + .. + } => numerator.contains_monospace_text() || denominator.contains_monospace_text(), + Self::MathChoice { + display, + text, + script, + scriptscript, + } => { + display.contains_monospace_text() + || text.contains_monospace_text() + || script.contains_monospace_text() + || scriptscript.contains_monospace_text() + } + Self::Root { index, body, .. } => { + body.contains_monospace_text() + || index.as_deref().is_some_and(Self::contains_monospace_text) + } + Self::Delimited { body, .. } => body.contains_monospace_text(), + Self::Fenced { segments, .. } => segments.iter().any(Self::contains_monospace_text), + Self::Script { + base, + sub, + superscript, + .. + } => { + base.contains_monospace_text() + || sub.as_deref().is_some_and(Self::contains_monospace_text) + || superscript + .as_deref() + .is_some_and(Self::contains_monospace_text) + } + Self::Text(_) + | Self::Atom { .. } + | Self::MathSpacingChange(_) + | Self::MathLineBreakPenaltiesChange(_) + | Self::BreakPenalty(_) + | Self::MathStyleChange(_) + | Self::Space(_) + | Self::Glue(_) + | Self::Kern(_) + | Self::SizedDelimiter { .. } + | Self::UnicodeDelimiter { .. } => false, + } + } + + pub fn leading_class(&self) -> Option { + match self { + Self::Spanned { expression, .. } => expression.leading_class(), + Self::Styled { expression, .. } => expression.leading_class(), + Self::Classified { class, .. } => Some(*class), + Self::Phantom { .. } => Some(MathClass::Ordinary), + Self::SizedDelimiter { class, .. } => Some(*class), + Self::UnicodeDelimiter { class, .. } => Some(*class), + Self::Accent { position, .. } => Some(math_accent_class(*position)), + Self::Text(_) | Self::TextStyled { .. } | Self::Atom { .. } | Self::Root { .. } => { + Some(self.class()) + } + Self::MathSpacingChange(_) + | Self::MathLineBreakPenaltiesChange(_) + | Self::BreakPenalty(_) + | Self::MathStyleChange(_) + | Self::Space(_) + | Self::Glue(_) + | Self::Kern(_) => None, + Self::Sequence(items) => items.iter().find_map(Self::leading_class).map(|class| { + if class == MathClass::Binary { + MathClass::Ordinary + } else { + class + } + }), + Self::MathChoice { display, .. } => display.leading_class(), + Self::Alignment { .. } + | Self::Fraction { .. } + | Self::Delimited { .. } + | Self::Fenced { .. } => Some(MathClass::Inner), + Self::Script { base, .. } => base.leading_class(), + } + } + + pub fn trailing_class(&self) -> Option { + match self { + Self::Spanned { expression, .. } => expression.trailing_class(), + Self::Styled { expression, .. } => expression.trailing_class(), + Self::Classified { class, .. } => Some(*class), + Self::Phantom { .. } => Some(MathClass::Ordinary), + Self::SizedDelimiter { class, .. } => Some(*class), + Self::UnicodeDelimiter { class, .. } => Some(*class), + Self::Accent { position, .. } => Some(math_accent_class(*position)), + Self::Text(_) | Self::TextStyled { .. } | Self::Atom { .. } | Self::Root { .. } => { + Some(self.class()) + } + Self::MathSpacingChange(_) + | Self::MathLineBreakPenaltiesChange(_) + | Self::BreakPenalty(_) + | Self::MathStyleChange(_) + | Self::Space(_) + | Self::Glue(_) + | Self::Kern(_) => None, + Self::Sequence(items) => { + items + .iter() + .rev() + .find_map(Self::trailing_class) + .map(|class| { + if class == MathClass::Binary { + MathClass::Ordinary + } else { + class + } + }) + } + Self::MathChoice { display, .. } => display.trailing_class(), + Self::Alignment { .. } + | Self::Fraction { .. } + | Self::Delimited { .. } + | Self::Fenced { .. } => Some(MathClass::Inner), + Self::Script { base, .. } => base.trailing_class(), + } + } + + pub fn class(&self) -> MathClass { + match self { + Self::Spanned { expression, .. } => expression.class(), + Self::Styled { expression, .. } => expression.class(), + Self::Classified { class, .. } => *class, + Self::Phantom { .. } => MathClass::Ordinary, + Self::Accent { position, .. } => math_accent_class(*position), + Self::Atom { class, .. } => *class, + Self::SizedDelimiter { class, .. } => *class, + Self::UnicodeDelimiter { class, .. } => *class, + Self::MathChoice { display, .. } => display.class(), + Self::Alignment { .. } + | Self::Fraction { .. } + | Self::Delimited { .. } + | Self::Fenced { .. } => MathClass::Inner, + Self::Script { base, .. } => base.class(), + Self::Sequence(items) => items + .iter() + .find_map(Self::leading_class) + .unwrap_or(MathClass::Ordinary), + Self::Text(_) + | Self::TextStyled { .. } + | Self::MathStyleChange(_) + | Self::Space(_) + | Self::Glue(_) + | Self::Kern(_) + | Self::MathSpacingChange(_) + | Self::MathLineBreakPenaltiesChange(_) + | Self::BreakPenalty(_) + | Self::Root { .. } => MathClass::Ordinary, + } + } + + pub fn uses_display_limits(&self) -> bool { + match self { + Self::Spanned { expression, .. } => expression.uses_display_limits(), + Self::Styled { expression, .. } => expression.uses_display_limits(), + Self::Classified { + class: MathClass::Operator, + .. + } => true, + Self::Accent { .. } => false, + Self::Atom { + class: MathClass::Operator, + text, + .. + } => matches!(text.as_str(), "∑" | "∏" | "lim" | "max" | "min"), + Self::Script { base, limits, .. } => match limits { + MathLimitMode::Automatic => base.uses_display_limits(), + MathLimitMode::DisplayLimits | MathLimitMode::Limits => true, + MathLimitMode::NoLimits => false, + }, + Self::MathChoice { display, .. } => display.uses_display_limits(), + _ => false, + } + } + + pub fn without_source(&self) -> Self { + match self { + Self::Spanned { expression, .. } => expression.without_source(), + Self::Styled { font, expression } => Self::Styled { + font: *font, + expression: Box::new(expression.without_source()), + }, + Self::Classified { class, body } => Self::Classified { + class: *class, + body: Box::new(body.without_source()), + }, + Self::Phantom { kind, body } => Self::Phantom { + kind: *kind, + body: Box::new(body.without_source()), + }, + Self::Accent { + position, + body, + family, + math_fonts, + } => Self::Accent { + position: *position, + body: Box::new(body.without_source()), + family: *family, + math_fonts: Arc::clone(math_fonts), + }, + Self::Sequence(items) => { + Self::Sequence(items.iter().map(Self::without_source).collect()) + } + Self::Alignment { + rows, + alignment, + baseline, + math_fonts, + cell_style, + row_spacing, + } => Self::Alignment { + rows: rows + .iter() + .map(|row| row.iter().map(Self::without_source).collect()) + .collect(), + alignment: alignment.clone(), + baseline: *baseline, + math_fonts: Arc::clone(math_fonts), + cell_style: *cell_style, + row_spacing: *row_spacing, + }, + Self::Fraction { + numerator, + denominator, + style, + has_rule, + rule_thickness, + math_fonts, + } => Self::Fraction { + numerator: Box::new(numerator.without_source()), + denominator: Box::new(denominator.without_source()), + style: *style, + has_rule: *has_rule, + rule_thickness: *rule_thickness, + math_fonts: Arc::clone(math_fonts), + }, + Self::MathChoice { + display, + text, + script, + scriptscript, + } => Self::MathChoice { + display: Box::new(display.without_source()), + text: Box::new(text.without_source()), + script: Box::new(script.without_source()), + scriptscript: Box::new(scriptscript.without_source()), + }, + Self::Root { + index, + body, + radical, + math_fonts, + } => Self::Root { + index: index + .as_deref() + .map(|index| Box::new(index.without_source())), + body: Box::new(body.without_source()), + radical: *radical, + math_fonts: Arc::clone(math_fonts), + }, + Self::Delimited { + left, + body, + right, + left_settings, + right_settings, + } => Self::Delimited { + left: left.clone(), + body: Box::new(body.without_source()), + right: right.clone(), + left_settings: *left_settings, + right_settings: *right_settings, + }, + Self::Fenced { + delimiters, + delimiter_settings, + segments, + } => Self::Fenced { + delimiters: delimiters.clone(), + delimiter_settings: delimiter_settings.clone(), + segments: segments.iter().map(Self::without_source).collect(), + }, + Self::Script { + base, + sub, + superscript, + limits, + } => Self::Script { + base: Box::new(base.without_source()), + sub: sub.as_deref().map(|sub| Box::new(sub.without_source())), + superscript: superscript + .as_deref() + .map(|superscript| Box::new(superscript.without_source())), + limits: *limits, + }, + _ => self.clone(), + } + } + + pub fn rebase_source_locations( + &mut self, + locations: &HashMap, + ) -> bool { + match self { + Self::Spanned { + location, + expression, + } => { + if let Some(location) = location { + let Some(rebased) = locations.get(location) else { + return false; + }; + *location = rebased.clone(); + } + expression.rebase_source_locations(locations) + } + Self::Styled { expression, .. } => expression.rebase_source_locations(locations), + Self::Classified { body, .. } | Self::Phantom { body, .. } => { + body.rebase_source_locations(locations) + } + Self::Accent { body, .. } => body.rebase_source_locations(locations), + Self::Sequence(items) => items + .iter_mut() + .all(|item| item.rebase_source_locations(locations)), + Self::Alignment { rows, .. } => rows + .iter_mut() + .flatten() + .all(|item| item.rebase_source_locations(locations)), + Self::Fraction { + numerator, + denominator, + .. + } => { + numerator.rebase_source_locations(locations) + && denominator.rebase_source_locations(locations) + } + Self::MathChoice { + display, + text, + script, + scriptscript, + } => { + display.rebase_source_locations(locations) + && text.rebase_source_locations(locations) + && script.rebase_source_locations(locations) + && scriptscript.rebase_source_locations(locations) + } + Self::Root { index, body, .. } => { + index + .as_deref_mut() + .is_none_or(|index| index.rebase_source_locations(locations)) + && body.rebase_source_locations(locations) + } + Self::Delimited { body, .. } => body.rebase_source_locations(locations), + Self::Fenced { segments, .. } => segments + .iter_mut() + .all(|segment| segment.rebase_source_locations(locations)), + Self::Script { + base, + sub, + superscript, + .. + } => { + base.rebase_source_locations(locations) + && sub + .as_deref_mut() + .is_none_or(|sub| sub.rebase_source_locations(locations)) + && superscript + .as_deref_mut() + .is_none_or(|superscript| superscript.rebase_source_locations(locations)) + } + Self::Text(_) + | Self::TextStyled { .. } + | Self::Atom { .. } + | Self::MathSpacingChange(_) + | Self::MathLineBreakPenaltiesChange(_) + | Self::BreakPenalty(_) + | Self::MathStyleChange(_) + | Self::Space(_) + | Self::Glue(_) + | Self::Kern(_) + | Self::SizedDelimiter { .. } + | Self::UnicodeDelimiter { .. } => true, + } + } +} + +/// Whether a math nucleus is a single character-like atom eligible for the +/// ordinary character script-placement rules. +pub fn is_character_like_math_nucleus(expression: &MathExpr) -> bool { + match expression { + MathExpr::Spanned { expression, .. } | MathExpr::Styled { expression, .. } => { + is_character_like_math_nucleus(expression) + } + MathExpr::Classified { + class: MathClass::Ordinary, + body, + } => is_character_like_math_nucleus(body), + MathExpr::Classified { .. } => false, + MathExpr::Atom { text, .. } => text.chars().count() == 1, + MathExpr::Accent { .. } + | MathExpr::Phantom { .. } + | MathExpr::Alignment { .. } + | MathExpr::SizedDelimiter { .. } + | MathExpr::UnicodeDelimiter { .. } + | MathExpr::Fraction { .. } + | MathExpr::Root { .. } + | MathExpr::Delimited { .. } + | MathExpr::Fenced { .. } + | MathExpr::Script { .. } + | MathExpr::Sequence(_) + | MathExpr::MathChoice { .. } + | MathExpr::MathSpacingChange(_) + | MathExpr::MathLineBreakPenaltiesChange(_) + | MathExpr::BreakPenalty(_) + | MathExpr::MathStyleChange(_) + | MathExpr::Space(_) + | MathExpr::Glue(_) + | MathExpr::Kern(_) + | MathExpr::TextStyled { .. } + | MathExpr::Text(_) => false, + } +} + +/// Whether a math nucleus has operator class after style wrappers. +pub fn is_operator_math_nucleus(expression: &MathExpr) -> bool { + match expression { + MathExpr::Spanned { expression, .. } | MathExpr::Styled { expression, .. } => { + is_operator_math_nucleus(expression) + } + MathExpr::Classified { class, .. } | MathExpr::Atom { class, .. } => { + *class == MathClass::Operator + } + _ => false, + } +} + +/// Whether the nucleus exposes exactly one glyph after transparent wrappers. +pub fn is_single_glyph_math_nucleus(expression: &MathExpr) -> bool { + match expression { + MathExpr::Spanned { expression, .. } + | MathExpr::Styled { expression, .. } + | MathExpr::Classified { + body: expression, .. + } => is_single_glyph_math_nucleus(expression), + MathExpr::Atom { text, .. } => text.chars().count() == 1, + _ => false, + } +} + +/// A character nucleus selected for OpenType MATH script-kern placement. +pub struct MathScriptGlyphCandidate<'a, Style> { + pub expression: &'a MathExpr, + pub style: Style, + pub math_style: MathStyle, +} + +/// Finds the first character nucleus used to kern an ordinary script. +/// +/// The callbacks let the font backend translate math-style changes and math +/// font wrappers into its own style type while this function owns the TeX list +/// traversal and skip rules. +pub fn first_script_math_glyph_candidate<'a, Style: Clone>( + expression: &'a MathExpr, + style: Style, + math_style: MathStyle, + style_for_math_style: impl Fn(&Style, MathStyle, MathStyle) -> Style, + style_for_font: impl Fn(&Style, MathFontStyle) -> Style, +) -> Option> { + fn find<'a, Style: Clone>( + expression: &'a MathExpr, + style: Style, + math_style: MathStyle, + style_for_math_style: &impl Fn(&Style, MathStyle, MathStyle) -> Style, + style_for_font: &impl Fn(&Style, MathFontStyle) -> Style, + ) -> Option> { + match expression { + MathExpr::Spanned { expression, .. } => find( + expression, + style, + math_style, + style_for_math_style, + style_for_font, + ), + MathExpr::Styled { font, expression } => find( + expression, + style_for_font(&style, *font), + math_style, + style_for_math_style, + style_for_font, + ), + MathExpr::Atom { class, .. } if *class != MathClass::Inner => { + Some(MathScriptGlyphCandidate { + expression, + style, + math_style, + }) + } + MathExpr::Sequence(expressions) => { + let initial_style = style.clone(); + let initial_math_style = math_style; + let mut current_style = style; + let mut current_math_style = math_style; + for expression in expressions { + if let Some(command) = crate::math_list::math_style_command(expression) { + let next_math_style = MathStyle::from_command(command); + current_style = style_for_math_style( + &initial_style, + initial_math_style, + next_math_style, + ); + current_math_style = next_math_style; + continue; + } + if is_math_kern_ignorable(expression) { + continue; + } + return find( + expression, + current_style, + current_math_style, + style_for_math_style, + style_for_font, + ); + } + None + } + MathExpr::MathChoice { .. } => find( + crate::math_list::math_choice_variant(expression, math_style), + style, + math_style, + style_for_math_style, + style_for_font, + ), + _ => None, + } + } + + find( + expression, + style, + math_style, + &style_for_math_style, + &style_for_font, + ) +} + +fn is_math_kern_ignorable(expression: &MathExpr) -> bool { + match expression { + MathExpr::Spanned { expression, .. } => is_math_kern_ignorable(expression), + MathExpr::MathStyleChange(_) + | MathExpr::Space(_) + | MathExpr::Glue(_) + | MathExpr::Kern(_) => true, + _ => false, + } +} + +pub fn is_cjk(character: char) -> bool { + matches!( + character as u32, + 0x2E80..=0x2EFF + | 0x2F00..=0x2FDF + | 0x3000..=0x30FF + | 0x3100..=0x31FF + | 0x3400..=0x4DBF + | 0x4E00..=0x9FFF + | 0xAC00..=0xD7AF + | 0xF900..=0xFAFF + | 0xFE30..=0xFE4F + | 0xFF00..=0xFFEF + | 0x20000..=0x2FA1F + ) +} + +pub fn format_script(source: &str, superscript: bool) -> String { + let mut converted = String::new(); + for character in source.chars() { + let mapped = if superscript { + superscript_character(character) + } else { + subscript_character(character) + }; + let Some(mapped) = mapped else { + return format!("{}({source})", if superscript { "^" } else { "_" }); + }; + converted.push(mapped); + } + converted +} + +fn superscript_character(character: char) -> Option { + Some(match character { + '0' => '⁰', + '1' => '¹', + '2' => '²', + '3' => '³', + '4' => '⁴', + '5' => '⁵', + '6' => '⁶', + '7' => '⁷', + '8' => '⁸', + '9' => '⁹', + '+' => '⁺', + '-' | '−' => '⁻', + '=' => '⁼', + '(' => '⁽', + ')' => '⁾', + 'n' => 'ⁿ', + 'i' => 'ⁱ', + 'a' => 'ᵃ', + 'b' => 'ᵇ', + 'c' => 'ᶜ', + 'd' => 'ᵈ', + 'e' => 'ᵉ', + 'f' => 'ᶠ', + 'g' => 'ᵍ', + 'h' => 'ʰ', + 'j' => 'ʲ', + 'k' => 'ᵏ', + 'l' => 'ˡ', + 'm' => 'ᵐ', + 'o' => 'ᵒ', + 'p' => 'ᵖ', + 'r' => 'ʳ', + 's' => 'ˢ', + 't' => 'ᵗ', + 'u' => 'ᵘ', + 'v' => 'ᵛ', + 'w' => 'ʷ', + 'x' => 'ˣ', + 'y' => 'ʸ', + 'z' => 'ᶻ', + _ => return None, + }) +} + +fn subscript_character(character: char) -> Option { + Some(match character { + '0' => '₀', + '1' => '₁', + '2' => '₂', + '3' => '₃', + '4' => '₄', + '5' => '₅', + '6' => '₆', + '7' => '₇', + '8' => '₈', + '9' => '₉', + '+' => '₊', + '-' | '−' => '₋', + '=' => '₌', + '(' => '₍', + ')' => '₎', + 'a' => 'ₐ', + 'e' => 'ₑ', + 'h' => 'ₕ', + 'i' => 'ᵢ', + 'j' => 'ⱼ', + 'k' => 'ₖ', + 'l' => 'ₗ', + 'm' => 'ₘ', + 'n' => 'ₙ', + 'o' => 'ₒ', + 'p' => 'ₚ', + 'r' => 'ᵣ', + 's' => 'ₛ', + 't' => 'ₜ', + 'u' => 'ᵤ', + 'v' => 'ᵥ', + 'x' => 'ₓ', + _ => return None, + }) +} diff --git a/crates/texrra-core/src/math_glyph.rs b/crates/texrra-core/src/math_glyph.rs new file mode 100644 index 0000000..edf3b87 --- /dev/null +++ b/crates/texrra-core/src/math_glyph.rs @@ -0,0 +1,137 @@ +use crate::MathClass; + +/// The corner of a math glyph used to query an OpenType MATH kern. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathKernCorner { + TopRight, + TopLeft, + BottomRight, + BottomLeft, +} + +/// The slant selected by TeX's ordinary math-atom family rules. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathAtomFontShape { + Inherited, + Upright, + Italic, +} + +/// Selects the font shape for a math atom before backend style conversion. +pub fn math_atom_font_shape(class: MathClass, math_family: Option) -> MathAtomFontShape { + if class != MathClass::Ordinary { + return MathAtomFontShape::Upright; + } + match math_family { + Some(1) => MathAtomFontShape::Italic, + Some(_) => MathAtomFontShape::Upright, + None => MathAtomFontShape::Inherited, + } +} + +/// Returns the characters represented by a math atom's stored source and slots. +pub fn math_atom_glyph_text(text: &str, math_family: Option, math_slots: &[u8]) -> String { + if math_family.is_some() + && math_slots.len() == text.chars().count() + && math_slots.iter().all(|slot| (b' '..=b'~').contains(slot)) + { + math_slots.iter().map(|slot| char::from(*slot)).collect() + } else { + text.to_string() + } +} + +/// Whether this atom's character is selected from the OpenType math face. +pub fn prefers_math_font( + class: MathClass, + character: char, + math_family: Option, + bold: bool, + italic: bool, +) -> bool { + let greek = is_greek_letter(character); + let unicode_math_alphanumeric = is_math_alphanumeric_character(character); + let is_math_symbol = !character.is_alphanumeric() || unicode_math_alphanumeric; + let is_math_italic_letter = class == MathClass::Ordinary + && character.is_ascii_alphabetic() + && (math_family == Some(1) || italic); + (is_math_symbol || greek || is_math_italic_letter) + && (!bold || unicode_math_alphanumeric) + && (!italic + || !character.is_alphanumeric() + || greek + || unicode_math_alphanumeric + || is_math_italic_letter) +} + +fn is_math_alphanumeric_character(character: char) -> bool { + matches!(character as u32, 0x1D400..=0x1D7FF) + || matches!( + character as u32, + 0x2102 + | 0x210A..=0x210E + | 0x2110..=0x2115 + | 0x2119..=0x211D + | 0x2124 + | 0x212C..=0x212F + | 0x2130..=0x2131 + | 0x2133..=0x2134 + ) +} + +fn is_greek_letter(character: char) -> bool { + character.is_alphabetic() && matches!(character as u32, 0x0370..=0x03FF | 0x1F00..=0x1FFF) +} + +/// Engine-owned kern breakpoints and values, measured in font design units. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct MathKernTable { + pub correction_heights: Vec>, + pub values: Vec>, +} + +/// MATH metrics for one glyph, independent of the font parser's table types. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct MathGlyphMetrics { + /// Italic correction. `Some(0)` means a correction table was present but + /// had no explicit entry for this glyph. + pub italic_correction: Option, + pub top_accent_attachment: Option, + pub top_right_kern: Option, + pub top_left_kern: Option, + pub bottom_right_kern: Option, + pub bottom_left_kern: Option, +} + +/// Return a glyph's MATH italic correction in design units. +pub fn italic_correction(metrics: &MathGlyphMetrics) -> Option { + metrics.italic_correction +} + +/// Return a glyph's top accent attachment point in design units. +pub fn top_accent_attachment(metrics: &MathGlyphMetrics) -> Option { + metrics.top_accent_attachment +} + +/// Select the MATH kern value for a corner and correction height. +/// +/// `correction_height` is expressed in the font's design units. OpenType kern +/// tables select the value following every breakpoint at or below that height. +pub fn math_kern_at_height( + metrics: &MathGlyphMetrics, + corner: MathKernCorner, + correction_height: f64, +) -> Option { + let kern = match corner { + MathKernCorner::TopRight => metrics.top_right_kern.as_ref(), + MathKernCorner::TopLeft => metrics.top_left_kern.as_ref(), + MathKernCorner::BottomRight => metrics.bottom_right_kern.as_ref(), + MathKernCorner::BottomLeft => metrics.bottom_left_kern.as_ref(), + }?; + let kern_index = kern + .correction_heights + .iter() + .take_while(|height| height.is_some_and(|height| f64::from(height) <= correction_height)) + .count(); + kern.values.get(kern_index).copied().flatten() +} diff --git a/crates/texrra-core/src/math_layout.rs b/crates/texrra-core/src/math_layout.rs new file mode 100644 index 0000000..9d949d0 --- /dev/null +++ b/crates/texrra-core/src/math_layout.rs @@ -0,0 +1,1513 @@ +use crate::math_expr::{ + MathAlignment, MathAlignmentBaseline, MathCellStyle, MathColumnAlignment, + MathDelimiterSettings, MathExpr, MathRowSpacing, MathSpacingSettings, +}; +use crate::math_glyph::MathKernCorner; +use crate::math_list::{ + MathBoundary, MathListContext, child_context, math_style_command, normalized_classes, +}; +use crate::{MathClass, MathStyle}; + +/// Computes XeTeX's requested height for a delimiter from its axis extents. +pub fn delimiter_target_height( + extent_above_axis: f64, + extent_below_axis: f64, + settings: MathDelimiterSettings, +) -> f64 { + const TEX_POINTS_PER_INCH: f64 = 72.27; + + let axis_distance = extent_above_axis.max(extent_below_axis); + let factor_target = axis_distance * f64::from(settings.factor) / 500.0; + let shortfall_mm = f64::from(settings.shortfall.0) / 65_536.0 * 25.4 / TEX_POINTS_PER_INCH; + let shortfall_target = axis_distance * 2.0 - shortfall_mm; + factor_target.max(shortfall_target) +} + +/// Places a delimiter glyph vertically against the math axis and baseline. +pub fn delimiter_top_from_baseline(baseline: f64, axis_height: f64, delimiter_height: f64) -> f64 { + baseline - axis_height - delimiter_height / 2.0 +} + +/// The dimensions of a measured delimiter glyph. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathDelimiterDimensions { + pub width: f64, + pub height: f64, +} + +/// Inputs for a body enclosed by left and right delimiters. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathDelimitedLayoutInput { + pub body: MathBoxDimensions, + pub axis_height: f64, + pub left: Option, + pub right: Option, +} + +/// Geometry for a body enclosed by left and right delimiters. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathDelimitedLayout { + pub width: f64, + pub height: f64, + pub baseline: f64, + pub left_x: f64, + pub left_y: Option, + pub body_x: f64, + pub body_y: f64, + pub right_x: f64, + pub right_y: Option, +} + +/// A point in a math box, in the caller's chosen coordinate unit. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathLayoutPosition { + pub x: f64, + pub y: f64, +} + +/// TeX state and neighboring classes needed to lay out one math-list item. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathSequenceItemPlan { + pub boundary: MathBoundary, + pub child_context: MathListContext, + pub math_style: MathStyle, + pub spacing: MathSpacingSettings, + pub is_metadata: bool, +} + +/// A measured child paired with its engine-computed math-list state. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathSequenceChildLayout { + pub dimensions: MathBoxDimensions, + pub plan: MathSequenceItemPlan, +} + +/// Dimensions and child placements for a horizontal math sequence. +#[derive(Clone, Debug, PartialEq)] +pub struct MathSequenceLayout { + pub width: f64, + pub height: f64, + pub baseline: f64, + /// Positions align with the input children; metadata items have no position. + pub child_positions: Vec>, +} + +/// Resolve style, spacing settings, class boundaries, and child contexts for a +/// math sequence before the font backend measures its items. +pub fn plan_math_sequence( + items: &[MathExpr], + math_style: MathStyle, + spacing: MathSpacingSettings, + list_context: MathListContext, +) -> Vec { + let classes = normalized_classes(items, math_style, list_context); + let mut current_math_style = math_style; + let mut current_spacing = spacing; + + items + .iter() + .enumerate() + .map(|(index, item)| { + let style_command = math_style_command(item); + if let Some(command) = style_command { + current_math_style = MathStyle::from_command(command); + } + if let MathExpr::MathSpacingChange(settings) = item { + current_spacing = *settings; + } + + MathSequenceItemPlan { + boundary: classes[index], + child_context: child_context(&classes, index, list_context), + math_style: current_math_style, + spacing: current_spacing, + is_metadata: style_command.is_some() + || matches!( + item, + MathExpr::MathSpacingChange(_) + | MathExpr::MathLineBreakPenaltiesChange(_) + | MathExpr::BreakPenalty(_) + ), + } + }) + .collect() +} + +/// Arrange measured math-list children around a shared baseline. +/// +/// The callback converts TeX's class-pair spacing into the caller's coordinate +/// unit using the active font metrics. +pub fn layout_math_sequence( + children: &[MathSequenceChildLayout], + baseline: f64, + mut inter_atom_spacing: impl FnMut(MathClass, MathClass, MathStyle, MathSpacingSettings) -> f64, +) -> MathSequenceLayout { + let mut top = baseline; + let mut bottom = baseline; + let mut width = 0.0; + let mut previous_class = None; + let mut child_positions = vec![None; children.len()]; + + for (index, child) in children.iter().enumerate() { + if child.plan.is_metadata { + continue; + } + if let (Some(previous), Some(next)) = (previous_class, child.plan.boundary.leading) { + width += inter_atom_spacing(previous, next, child.plan.math_style, child.plan.spacing); + } + + let child_y = baseline - child.dimensions.baseline; + top = top.min(child_y); + bottom = bottom.max(child_y + child.dimensions.height); + child_positions[index] = Some(MathLayoutPosition { + x: width, + y: child_y, + }); + width += child.dimensions.width; + previous_class = child.plan.boundary.trailing.or(previous_class); + } + + let shift = -top; + for position in child_positions.iter_mut().flatten() { + position.y += shift; + } + + MathSequenceLayout { + width, + height: bottom - top, + baseline: baseline + shift, + child_positions, + } +} + +/// Inputs for the horizontal and vertical placement of a fenced math row. +/// +/// The delimiter and spacing slices must contain one more item than `segments`. +#[derive(Clone, Debug, PartialEq)] +pub struct MathFencedLayoutInput<'a> { + pub segments: &'a [MathBoxDimensions], + pub delimiters: &'a [Option], + pub spacing_before_delimiter: &'a [f64], + pub spacing_after_delimiter: &'a [f64], + pub baseline: f64, + pub axis_height: f64, +} + +/// Geometry and child positions for a fenced math row. +#[derive(Clone, Debug, PartialEq)] +pub struct MathFencedLayout { + pub width: f64, + pub height: f64, + pub baseline: f64, + pub delimiter_positions: Vec>, + pub segment_positions: Vec, +} + +/// Inputs for positioning a math accent above or below its nucleus. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathAccentLayoutInput { + pub body: MathBoxDimensions, + pub accent_width: f64, + pub accent_height: f64, + pub accent_advance: Option, + pub accent_offset_x: f64, + pub body_attachment: Option, + pub accent_attachment: Option, + pub above: bool, + pub accent_delta: Option, + pub base_top_from_baseline: Option, + pub paint_baseline_from_top: Option, + pub paint_ink_bottom_from_top: Option, + pub gap: f64, + pub extra_space: f64, +} + +/// Geometry for an accented math box and its two child positions. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathAccentLayout { + pub width: f64, + pub height: f64, + pub baseline: f64, + pub body_position: MathLayoutPosition, + pub accent_position: MathLayoutPosition, +} + +/// A vertical rule position inside an array-like math alignment box. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathAlignmentRule { + pub x: f64, + pub y: f64, + pub width: f64, + pub height: f64, +} + +/// Inputs for laying out the measured cells of an alignment environment. +#[derive(Clone, Debug, PartialEq)] +pub struct MathAlignmentLayoutInput<'a> { + pub rows: &'a [Vec], + pub alignment: &'a MathAlignment, + pub cell_style: MathCellStyle, + pub row_spacing: MathRowSpacing, + pub equation_row_gap: f64, + pub strut_ascent: f64, + pub strut_descent: f64, + pub intercolumn_space: f64, + pub script_intercolumn_space: f64, + pub array_column_separation: f64, + pub array_rule_thickness: f64, + pub array_rule_gap: f64, + pub math_axis_height: f64, + pub baseline_mode: MathAlignmentBaseline, +} + +/// Positions and overall dimensions for an alignment environment. +#[derive(Clone, Debug, PartialEq)] +pub struct MathAlignmentLayout { + pub width: f64, + pub height: f64, + pub baseline: f64, + pub cell_positions: Vec>, + pub rules: Vec, +} + +/// Lays out alignment cells, rows, and optional array rules using TeX geometry. +pub fn layout_math_alignment(input: MathAlignmentLayoutInput<'_>) -> MathAlignmentLayout { + let MathAlignmentLayoutInput { + rows, + alignment, + cell_style, + row_spacing, + equation_row_gap, + strut_ascent, + strut_descent, + intercolumn_space, + script_intercolumn_space, + array_column_separation, + array_rule_thickness, + array_rule_gap, + math_axis_height, + baseline_mode, + } = input; + let column_count = rows + .iter() + .map(Vec::len) + .max() + .unwrap_or(0) + .max(match alignment { + MathAlignment::ArrayColumns { columns, .. } => columns.len(), + _ => 0, + }); + assert!(column_count > 0); + + let mut column_widths = vec![0.0_f64; column_count]; + let mut row_metrics = Vec::with_capacity(rows.len()); + for row in rows { + let ascent = row.iter().map(|cell| cell.baseline).fold(0.0, f64::max); + let descent = row + .iter() + .map(|cell| (cell.height - cell.baseline).max(0.0)) + .fold(0.0, f64::max); + for (column, cell) in row.iter().enumerate() { + column_widths[column] = column_widths[column].max(cell.width); + } + row_metrics.push((ascent, descent)); + } + + for (ascent, descent) in &mut row_metrics { + *ascent = (*ascent).max(strut_ascent); + *descent = (*descent).max(strut_descent); + } + let row_gap = match row_spacing { + MathRowSpacing::Array => 0.0, + MathRowSpacing::Equation(_) => equation_row_gap, + MathRowSpacing::Cases => { + let stretched_ascent = strut_ascent * 1.2; + let stretched_descent = strut_descent * 1.2; + for (ascent, descent) in &mut row_metrics { + *ascent = (*ascent).max(stretched_ascent); + *descent = (*descent).max(stretched_descent); + } + 0.0 + } + }; + + let mut column_offsets = vec![0.0; column_count]; + if let MathAlignment::ArrayColumns { vertical_rules, .. } = alignment { + let leading_rules = vertical_rules.first().copied().unwrap_or(0); + column_offsets[0] = array_column_separation + + array_rule_pack_width(leading_rules, array_rule_thickness, array_rule_gap) + + if leading_rules > 0 { + array_column_separation + } else { + 0.0 + }; + } + for column in 1..column_count { + let gap = match alignment { + MathAlignment::AlternatingTight | MathAlignment::Multline => 0.0, + MathAlignment::Alternating if column % 2 == 0 => intercolumn_space, + MathAlignment::Alternating => 0.0, + MathAlignment::ArrayColumns { vertical_rules, .. } => { + array_column_separation * 2.0 + + array_rule_pack_width( + vertical_rules.get(column).copied().unwrap_or(0), + array_rule_thickness, + array_rule_gap, + ) + } + _ if cell_style == MathCellStyle::Script => script_intercolumn_space, + _ => intercolumn_space, + }; + column_offsets[column] = column_offsets[column - 1] + column_widths[column - 1] + gap; + } + let last_column_end = column_offsets[column_count - 1] + column_widths[column_count - 1]; + let width = match alignment { + MathAlignment::ArrayColumns { vertical_rules, .. } => { + let trailing_rules = vertical_rules.get(column_count).copied().unwrap_or(0); + last_column_end + + array_column_separation + + array_rule_pack_width(trailing_rules, array_rule_thickness, array_rule_gap) + + if trailing_rules > 0 { + array_column_separation + } else { + 0.0 + } + } + _ => last_column_end, + }; + + let mut height = 0.0; + let mut first_row_baseline = 0.0; + let mut cell_positions = Vec::with_capacity(rows.len()); + for (row_index, row) in rows.iter().enumerate() { + let (ascent, descent) = row_metrics[row_index]; + if row_index == 0 { + first_row_baseline = ascent; + } + let mut row_positions = Vec::with_capacity(row.len()); + for (column, cell) in row.iter().enumerate() { + let column_alignment = match alignment { + MathAlignment::Multline if row_metrics.len() == 1 => MathColumnAlignment::Center, + MathAlignment::Multline if row_index == 0 => MathColumnAlignment::Left, + MathAlignment::Multline if row_index + 1 == row_metrics.len() => { + MathColumnAlignment::Right + } + MathAlignment::Multline => MathColumnAlignment::Center, + MathAlignment::Alternating | MathAlignment::AlternatingTight + if column_count == 1 => + { + MathColumnAlignment::Center + } + MathAlignment::Alternating | MathAlignment::AlternatingTight if column % 2 == 0 => { + MathColumnAlignment::Right + } + MathAlignment::Alternating | MathAlignment::AlternatingTight => { + MathColumnAlignment::Left + } + MathAlignment::Centered => MathColumnAlignment::Center, + MathAlignment::Left => MathColumnAlignment::Left, + MathAlignment::Columns(columns) => columns + .get(column) + .copied() + .unwrap_or(MathColumnAlignment::Center), + MathAlignment::ArrayColumns { columns, .. } => columns + .get(column) + .copied() + .unwrap_or(MathColumnAlignment::Center), + }; + let x = match column_alignment { + MathColumnAlignment::Left => column_offsets[column], + MathColumnAlignment::Center => { + column_offsets[column] + (column_widths[column] - cell.width) / 2.0 + } + MathColumnAlignment::Right => { + column_offsets[column] + column_widths[column] - cell.width + } + }; + row_positions.push(MathLayoutPosition { + x, + y: height + ascent - cell.baseline, + }); + } + cell_positions.push(row_positions); + height += ascent + descent; + if row_index + 1 < row_metrics.len() { + height += row_gap; + } + } + + let mut rules = Vec::new(); + if let MathAlignment::ArrayColumns { vertical_rules, .. } = alignment { + for boundary in 0..=column_count { + let Some(rule_count) = vertical_rules.get(boundary).copied() else { + continue; + }; + let boundary_start = if boundary == 0 { + 0.0 + } else { + column_offsets[boundary - 1] + column_widths[boundary - 1] + }; + let mut x = boundary_start + array_column_separation; + for _ in 0..rule_count { + rules.push(MathAlignmentRule { + x: x - array_rule_thickness / 2.0, + y: 0.0, + width: array_rule_thickness, + height, + }); + x += array_rule_thickness + array_rule_gap; + } + } + } + + let baseline = match baseline_mode { + MathAlignmentBaseline::FirstRow => first_row_baseline, + MathAlignmentBaseline::MathAxisCentered => height / 2.0 + math_axis_height, + }; + MathAlignmentLayout { + width, + height, + baseline, + cell_positions, + rules, + } +} + +fn array_rule_pack_width(rule_count: usize, rule_thickness: f64, rule_gap: f64) -> f64 { + if rule_count == 0 { + 0.0 + } else { + rule_count as f64 * rule_thickness + (rule_count - 1) as f64 * rule_gap + } +} + +/// Places a measured accent relative to its nucleus and computes the enclosing box. +pub fn layout_math_accent(input: MathAccentLayoutInput) -> MathAccentLayout { + let MathAccentLayoutInput { + body, + accent_width, + accent_height, + accent_advance, + accent_offset_x, + body_attachment, + accent_attachment, + above, + accent_delta, + base_top_from_baseline, + paint_baseline_from_top, + paint_ink_bottom_from_top, + gap, + extra_space, + } = input; + let accent_width = accent_width.max(accent_advance.unwrap_or(accent_width)); + let advance_offset = accent_advance + .map(|advance| (accent_width - advance) / 2.0) + .unwrap_or(0.0); + let paint_attachment = accent_attachment + .map(|attachment| advance_offset + attachment) + .unwrap_or(accent_width / 2.0); + let accent_x = body_attachment + .map(|attachment| attachment - paint_attachment) + .unwrap_or((body.width - accent_width) / 2.0) + + advance_offset + + accent_offset_x; + + let accent_anchor_y = if above { + body.baseline - base_top_from_baseline.unwrap_or(body.baseline) - gap + } else { + 0.0 + }; + let accent_y = if above { + match ( + accent_delta, + paint_baseline_from_top, + paint_ink_bottom_from_top, + ) { + (Some(delta), Some(baseline), _) => delta - baseline, + (_, _, Some(ink_bottom)) => accent_anchor_y - ink_bottom, + _ => accent_anchor_y - accent_height, + } + } else { + body.height + gap + }; + let top = if above { + 0.0_f64.min(accent_y - extra_space) + } else { + 0.0 + }; + let bottom = body.height.max(accent_y + accent_height) + if above { 0.0 } else { extra_space }; + let shift = -top; + + MathAccentLayout { + width: body.width, + height: bottom - top, + baseline: body.baseline + shift, + body_position: MathLayoutPosition { x: 0.0, y: shift }, + accent_position: MathLayoutPosition { + x: accent_x, + y: accent_y + shift, + }, + } +} + +/// Places measured segments and delimiters on one math row. +pub fn layout_fenced_box(input: MathFencedLayoutInput<'_>) -> MathFencedLayout { + let MathFencedLayoutInput { + segments, + delimiters, + spacing_before_delimiter, + spacing_after_delimiter, + baseline, + axis_height, + } = input; + assert_eq!(delimiters.len(), segments.len() + 1); + assert_eq!(spacing_before_delimiter.len(), delimiters.len()); + assert_eq!(spacing_after_delimiter.len(), delimiters.len()); + + let mut x = 0.0; + let mut delimiter_x = vec![0.0; delimiters.len()]; + let mut segment_x = vec![0.0; segments.len()]; + for index in 0..segments.len() { + x += spacing_before_delimiter[index]; + delimiter_x[index] = x; + x += delimiters[index] + .map(|delimiter| delimiter.width) + .unwrap_or(0.0); + x += spacing_after_delimiter[index]; + segment_x[index] = x; + x += segments[index].width; + } + let last_delimiter = delimiters.len() - 1; + x += spacing_before_delimiter[last_delimiter]; + delimiter_x[last_delimiter] = x; + x += delimiters[last_delimiter] + .map(|delimiter| delimiter.width) + .unwrap_or(0.0); + + let mut top = 0.0_f64; + let mut bottom = baseline; + for segment in segments { + let y = baseline - segment.baseline; + top = top.min(y); + bottom = bottom.max(y + segment.height); + } + let delimiter_y = delimiters + .iter() + .map(|delimiter| { + delimiter.map(|delimiter| { + delimiter_top_from_baseline(baseline, axis_height, delimiter.height) + }) + }) + .collect::>(); + for (delimiter, y) in delimiters.iter().zip(&delimiter_y) { + if let (Some(delimiter), Some(y)) = (delimiter, y) { + top = top.min(*y); + bottom = bottom.max(*y + delimiter.height); + } + } + + let shift = -top; + MathFencedLayout { + width: x, + height: bottom - top, + baseline: baseline + shift, + delimiter_positions: delimiter_x + .into_iter() + .zip(delimiter_y) + .map(|(x, y)| y.map(|y| MathLayoutPosition { x, y: y + shift })) + .collect(), + segment_positions: segment_x + .into_iter() + .zip(segments) + .map(|(x, segment)| MathLayoutPosition { + x, + y: baseline - segment.baseline + shift, + }) + .collect(), + } +} + +/// Places measured delimiters around a laid-out math body. +pub fn layout_delimited_box(input: MathDelimitedLayoutInput) -> MathDelimitedLayout { + let MathDelimitedLayoutInput { + body, + axis_height, + left, + right, + } = input; + let left_width = left.map(|delimiter| delimiter.width).unwrap_or(0.0); + let right_width = right.map(|delimiter| delimiter.width).unwrap_or(0.0); + let left_y = left + .map(|delimiter| delimiter_top_from_baseline(body.baseline, axis_height, delimiter.height)); + let right_y = right + .map(|delimiter| delimiter_top_from_baseline(body.baseline, axis_height, delimiter.height)); + let top = left_y.into_iter().chain(right_y).fold(0.0_f64, f64::min); + let bottom = left + .zip(left_y) + .map(|(delimiter, y)| y + delimiter.height) + .into_iter() + .chain( + right + .zip(right_y) + .map(|(delimiter, y)| y + delimiter.height), + ) + .fold(body.height, f64::max); + let shift = -top; + + MathDelimitedLayout { + width: left_width + body.width + right_width, + height: bottom - top, + baseline: body.baseline + shift, + left_x: 0.0, + left_y: left_y.map(|y| y + shift), + body_x: left_width, + body_y: shift, + right_x: left_width + body.width, + right_y: right_y.map(|y| y + shift), + } +} + +/// Width, height, and baseline of a laid-out math child. +/// +/// Values use one consistent coordinate unit chosen by the caller. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathBoxDimensions { + pub width: f64, + pub height: f64, + pub baseline: f64, +} + +/// A measured child box inside a display-math alignment. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathDisplayChildBox { + pub x: f64, + pub y: f64, + pub dimensions: MathBoxDimensions, +} + +/// Vertical extent and right edge of one display-math row. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathDisplayRow { + pub baseline: f64, + pub top: f64, + pub bottom: f64, + pub right_edge: f64, +} + +/// The layout of equation numbers beside or below display-math rows. +#[derive(Clone, Debug, PartialEq)] +pub struct MathDisplayTagLayout { + pub baselines: Vec>, + pub row_shifts: Vec, + pub top_padding: f64, + pub height: f64, +} + +/// Whether an expression's outer structure is an alignment box. +pub fn is_alignment_expression(expression: &MathExpr) -> bool { + match expression { + MathExpr::Spanned { expression, .. } + | MathExpr::Styled { expression, .. } + | MathExpr::Classified { + body: expression, .. + } => is_alignment_expression(expression), + MathExpr::Sequence(items) if items.len() == 1 => is_alignment_expression(&items[0]), + MathExpr::Alignment { .. } => true, + _ => false, + } +} + +/// Return the row count for an outer `multline` alignment. +pub fn multline_row_count(expression: &MathExpr) -> Option { + match expression { + MathExpr::Spanned { expression, .. } + | MathExpr::Styled { expression, .. } + | MathExpr::Classified { + body: expression, .. + } => multline_row_count(expression), + MathExpr::Sequence(items) if items.len() == 1 => multline_row_count(&items[0]), + MathExpr::Alignment { + rows, + alignment: MathAlignment::Multline, + .. + } => Some(rows.len()), + _ => None, + } +} + +/// Group measured alignment cells by baseline into display-math rows. +pub fn display_math_rows( + expression: &MathExpr, + layout: MathBoxDimensions, + children: &[MathDisplayChildBox], +) -> Vec { + let fallback = || { + vec![MathDisplayRow { + baseline: layout.baseline, + top: 0.0, + bottom: layout.height, + right_edge: layout.width, + }] + }; + if !is_alignment_expression(expression) { + return fallback(); + } + + let mut rows = Vec::::new(); + for child in children { + let baseline = child.y + child.dimensions.baseline; + let top = child.y; + let bottom = child.y + child.dimensions.height; + let right_edge = child.x + child.dimensions.width; + if let Some(row) = rows + .iter_mut() + .find(|row| (row.baseline - baseline).abs() < 0.001) + { + row.top = row.top.min(top); + row.bottom = row.bottom.max(bottom); + if child.dimensions.width > 0.0 { + row.right_edge = row.right_edge.max(right_edge); + } + } else { + rows.push(MathDisplayRow { + baseline, + top, + bottom, + right_edge: if child.dimensions.width > 0.0 { + right_edge + } else { + 0.0 + }, + }); + } + } + rows.sort_by(|left, right| left.baseline.total_cmp(&right.baseline)); + if rows.is_empty() { fallback() } else { rows } +} + +/// Compute the per-row horizontal expansion used by `multline`. +pub fn multline_row_x_shifts( + expression: &MathExpr, + current_width: f64, + requested_width: f64, + child_count: usize, +) -> Option<(f64, Vec)> { + let row_count = multline_row_count(expression)?; + if child_count != row_count { + return None; + } + + let target_width = requested_width.max(current_width); + let extra_width = target_width - current_width; + let shifts = (0..row_count) + .map(|row_index| { + if row_count == 1 { + extra_width / 2.0 + } else if row_index == 0 { + 0.0 + } else if row_index + 1 == row_count { + extra_width + } else { + extra_width / 2.0 + } + }) + .collect(); + Some((target_width, shifts)) +} + +/// Select the math-row baselines used by a sequence of equation numbers. +pub fn equation_number_baselines( + expression: &MathExpr, + layout_baseline: f64, + number_count: usize, + rows: &[MathDisplayRow], +) -> Vec { + let row_baselines = rows.iter().map(|row| row.baseline).collect::>(); + if multline_row_count(expression).is_some() && number_count == 1 { + return vec![row_baselines.last().copied().unwrap_or(layout_baseline)]; + } + if number_count > 1 { + return row_baselines; + } + vec![layout_baseline] +} + +/// Select the display row associated with one equation number. +pub fn equation_tag_row_index( + expression: &MathExpr, + number_count: usize, + tag_baselines: &[f64], + rows: &[MathDisplayRow], + tag_index: usize, +) -> usize { + if rows.is_empty() { + return 0; + } + let has_row_tags = number_count > 1 || multline_row_count(expression).is_some(); + if !is_alignment_expression(expression) || !has_row_tags { + return rows.len() - 1; + } + + let Some(tag_baseline) = tag_baselines.get(tag_index) else { + return rows.len() - 1; + }; + rows.iter() + .enumerate() + .min_by(|(_, left), (_, right)| { + (left.baseline - tag_baseline) + .abs() + .total_cmp(&(right.baseline - tag_baseline).abs()) + }) + .map_or(rows.len() - 1, |(index, _)| index) +} + +/// Return the horizontal extent that must be kept clear beside an equation tag. +pub fn equation_tag_row_right_edge( + expression: &MathExpr, + layout_width: f64, + number_count: usize, + tag_baselines: &[f64], + rows: &[MathDisplayRow], + tag_index: usize, +) -> f64 { + let has_row_tags = number_count > 1 || multline_row_count(expression).is_some(); + if !is_alignment_expression(expression) || !has_row_tags { + return layout_width; + } + rows.get(equation_tag_row_index( + expression, + number_count, + tag_baselines, + rows, + tag_index, + )) + .map_or(layout_width, |row| row.right_edge) +} + +/// Choose a centered formula origin that keeps equation numbers clear. +pub fn display_formula_x( + expression: &MathExpr, + content_width: f64, + layout_width: f64, + tag_widths: &[Option], + tag_separation: f64, + tag_baselines: &[f64], + rows: &[MathDisplayRow], +) -> f64 { + let centered = (content_width - layout_width) / 2.0; + let tag_width = tag_widths.iter().flatten().copied().fold(0.0_f64, f64::max); + if tag_width == 0.0 { + return centered; + } + + if multline_row_count(expression).is_some() { + let tag_index = tag_widths.iter().position(Option::is_some).unwrap_or(0); + let row_right = equation_tag_row_right_edge( + expression, + layout_width, + tag_widths.len(), + tag_baselines, + rows, + tag_index, + ); + let number_width = tag_widths + .get(tag_index) + .copied() + .flatten() + .unwrap_or(tag_width); + if number_width == 0.0 { + return centered; + } + let safe_x = content_width - number_width - tag_separation - row_right; + return if safe_x < 0.0 { + 0.0 + } else { + centered.min(safe_x) + }; + } + + let mut safe_x = None; + for (tag_index, number_width) in tag_widths.iter().enumerate() { + let Some(number_width) = number_width else { + continue; + }; + if *number_width == 0.0 { + continue; + } + let row_right = equation_tag_row_right_edge( + expression, + layout_width, + tag_widths.len(), + tag_baselines, + rows, + tag_index, + ); + let candidate = content_width - number_width - tag_separation - row_right; + if candidate >= 0.0 { + safe_x = Some(safe_x.map_or(candidate, |current: f64| current.min(candidate))); + } + } + safe_x.map_or(centered, |safe_x| centered.min(safe_x)) +} + +/// Measure the width reserved for an outer `multline` formula. +pub fn display_formula_width( + expression: &MathExpr, + content_width: f64, + tag_width: f64, + tag_separation: f64, +) -> f64 { + if multline_row_count(expression).is_some() && tag_width > 0.0 { + (content_width - tag_width - tag_separation).max(0.0) + } else { + content_width + } +} + +/// Compute equation-number baselines, row shifts, and total display height. +pub fn layout_display_equation_tags( + expression: &MathExpr, + layout: MathBoxDimensions, + rows: &[MathDisplayRow], + tag_widths: &[Option], + content_width: f64, + formula_x: f64, + number_ascent: f64, + line_height: f64, + tag_separation: f64, +) -> MathDisplayTagLayout { + let row_baselines = + equation_number_baselines(expression, layout.baseline, tag_widths.len(), rows); + let fallback_row = MathDisplayRow { + baseline: layout.baseline, + top: 0.0, + bottom: layout.height, + right_edge: layout.width, + }; + let mut row_shifts = vec![0.0; rows.len()]; + let mut shifted_counts = vec![0usize; rows.len()]; + let mut top_padding: f64 = 0.0; + let mut baselines = Vec::with_capacity(tag_widths.len()); + for (index, tag_width) in tag_widths.iter().enumerate() { + let Some(tag_width) = tag_width else { + baselines.push(None); + continue; + }; + if row_baselines.get(index).is_none() { + baselines.push(None); + continue; + } + let row_index = + equation_tag_row_index(expression, tag_widths.len(), &row_baselines, rows, index); + let row = rows.get(row_index).copied().unwrap_or(fallback_row); + let preceding_shift = row_shifts.iter().take(row_index).sum::(); + let row_baseline = row.baseline + preceding_shift; + if *tag_width > 0.0 + && formula_x + row.right_edge + tag_width + tag_separation > content_width + { + let baseline = row.bottom + + preceding_shift + + tag_separation + + number_ascent + + line_height * shifted_counts[row_index] as f64; + baselines.push(Some(baseline)); + shifted_counts[row_index] += 1; + row_shifts[row_index] += tag_separation + line_height; + } else { + top_padding = top_padding.max((number_ascent - row_baseline).max(0.0)); + baselines.push(Some(row_baseline)); + } + } + let height = layout.height + top_padding + row_shifts.iter().sum::(); + MathDisplayTagLayout { + baselines, + row_shifts, + top_padding, + height, + } +} + +/// Return one vertical offset per child and the total height added by row shifts. +pub fn display_row_child_shifts( + rows: &[MathDisplayRow], + child_baselines: &[f64], + row_shifts: &[f64], +) -> (Vec, f64) { + let total_height = row_shifts.iter().sum::(); + if rows.is_empty() || total_height == 0.0 { + return (vec![0.0; child_baselines.len()], 0.0); + } + + let child_shifts = child_baselines + .iter() + .map(|baseline| { + let row_index = rows + .iter() + .enumerate() + .min_by(|(_, left), (_, right)| { + (left.baseline - baseline) + .abs() + .total_cmp(&(right.baseline - baseline).abs()) + }) + .map_or(0, |(index, _)| index); + row_shifts.iter().take(row_index).sum::() + }) + .collect(); + (child_shifts, total_height) +} + +/// Physical parameters used to place the numerator, denominator, and rule. +/// +/// Values use the same coordinate unit as [`MathBoxDimensions`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathFractionLayoutInput { + pub numerator: MathBoxDimensions, + pub denominator: MathBoxDimensions, + pub numerator_shift_up: f64, + pub denominator_shift_down: f64, + pub numerator_gap_min: f64, + pub denominator_gap_min: f64, + pub rule_thickness: f64, + pub stack_gap_min: f64, + pub axis_height: f64, + pub draw_rule: bool, +} + +/// Geometry for a TeX fraction box, including child positions and rule center. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathFractionLayout { + pub width: f64, + pub height: f64, + pub baseline: f64, + pub numerator_x: f64, + pub numerator_y: f64, + pub denominator_x: f64, + pub denominator_y: f64, + pub rule_y: Option, +} + +/// Places a fraction's already-laid-out children according to TeX math rules. +pub fn layout_fraction_box(input: MathFractionLayoutInput) -> MathFractionLayout { + let MathFractionLayoutInput { + numerator, + denominator, + mut numerator_shift_up, + mut denominator_shift_down, + numerator_gap_min, + denominator_gap_min, + rule_thickness, + stack_gap_min, + axis_height, + draw_rule, + } = input; + + let numerator_depth = numerator.height - numerator.baseline; + if draw_rule { + numerator_shift_up = numerator_shift_up + .max(axis_height + rule_thickness / 2.0 + numerator_gap_min + numerator_depth); + denominator_shift_down = denominator_shift_down + .max(denominator.baseline - axis_height + rule_thickness / 2.0 + denominator_gap_min); + } else { + let current_gap = (numerator_shift_up - numerator_depth) + - (denominator.baseline - denominator_shift_down); + let extra_shift = ((stack_gap_min - current_gap) / 2.0).max(0.0); + numerator_shift_up += extra_shift; + denominator_shift_down += extra_shift; + } + + let numerator_y = -numerator_shift_up - numerator.baseline; + let denominator_y = denominator_shift_down - denominator.baseline; + let rule_y = -axis_height; + let mut top = 0.0_f64.min(numerator_y).min(denominator_y); + let mut bottom = 0.0_f64 + .max(numerator_y + numerator.height) + .max(denominator_y + denominator.height); + if draw_rule { + top = top.min(rule_y - rule_thickness / 2.0); + bottom = bottom.max(rule_y + rule_thickness / 2.0); + } + + let shift = -top; + let width = numerator.width.max(denominator.width); + MathFractionLayout { + width, + height: bottom - top, + baseline: shift, + numerator_x: (width - numerator.width) / 2.0, + numerator_y: numerator_y + shift, + denominator_x: (width - denominator.width) / 2.0, + denominator_y: denominator_y + shift, + rule_y: draw_rule.then_some(rule_y + shift), + } +} + +/// The script-placement constraints needed for a non-limit script pair. +/// +/// Values use the same coordinate unit as [`MathBoxDimensions`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathScriptLayoutMetrics { + pub subscript_top_max: f64, + pub subscript_baseline_drop_min: f64, + pub subscript_shift_down: f64, + pub superscript_bottom_min: f64, + pub superscript_baseline_drop_max: f64, + pub superscript_bottom_max_with_subscript: f64, + pub superscript_shift_up: f64, + pub superscript_shift_up_cramped: f64, + pub sub_superscript_gap_min: f64, +} + +/// Inputs for placing ordinary superscripts and subscripts around a nucleus. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathScriptLayoutInput { + pub base: MathBoxDimensions, + pub subscript: Option, + pub superscript: Option, + pub metrics: MathScriptLayoutMetrics, + pub character_like_base: bool, + pub cramped: bool, +} + +/// Which side of the nucleus contains the ordinary script. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MathScriptSide { + Superscript, + Subscript, +} + +/// Ink bounds for a math glyph relative to its baseline. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathScriptGlyphBounds { + pub top: f64, + pub bottom: f64, +} + +/// Measured inputs for OpenType MATH script-kern placement. +/// +/// All values use the same coordinate unit. Kern lookup closures receive +/// correction heights in that unit and return kern values in the same unit. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathScriptKernInput { + pub base: MathScriptGlyphBounds, + pub script: MathScriptGlyphBounds, + pub vertical_shift: f64, + pub side: MathScriptSide, +} + +/// Vertical positions for a nucleus and its ordinary scripts. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathScriptLayout { + pub height: f64, + pub baseline: f64, + pub base_y: f64, + pub superscript_shift_up: Option, + pub superscript_y: Option, + pub subscript_shift_down: Option, + pub subscript_y: Option, +} + +/// Selects XeTeX's larger corner-kern sum for one ordinary math script. +pub fn math_script_kern( + input: MathScriptKernInput, + base_kern_at_height: impl Fn(MathKernCorner, f64) -> Option, + script_kern_at_height: impl Fn(MathKernCorner, f64) -> Option, +) -> f64 { + let MathScriptKernInput { + base, + script, + vertical_shift, + side, + } = input; + let base_kern = |corner, height| base_kern_at_height(corner, height).unwrap_or(0.0); + let script_kern = |corner, height| script_kern_at_height(corner, height).unwrap_or(0.0); + + match side { + MathScriptSide::Superscript => { + let sum_at_script_bottom = + base_kern(MathKernCorner::TopRight, vertical_shift + script.bottom) + + script_kern(MathKernCorner::BottomLeft, script.bottom); + let sum_at_base_top = base_kern(MathKernCorner::TopRight, base.top) + + script_kern(MathKernCorner::BottomLeft, base.top - vertical_shift); + sum_at_script_bottom.max(sum_at_base_top) + } + MathScriptSide::Subscript => { + let sum_at_script_top = + base_kern(MathKernCorner::BottomRight, -vertical_shift + script.top) + + script_kern(MathKernCorner::TopLeft, script.top); + let sum_at_base_bottom = base_kern(MathKernCorner::BottomRight, base.bottom) + + script_kern(MathKernCorner::TopLeft, base.bottom + vertical_shift); + sum_at_script_top.max(sum_at_base_bottom) + } + } +} + +/// Applies TeX's script shift, clearance, and combined-script constraints. +pub fn layout_scripts_vertical(input: MathScriptLayoutInput) -> MathScriptLayout { + let MathScriptLayoutInput { + base, + subscript, + superscript, + metrics, + character_like_base, + cramped, + } = input; + let base_depth = base.height - base.baseline; + let mut superscript_shift_up = if character_like_base { + 0.0 + } else { + (base.baseline - metrics.superscript_baseline_drop_max).max(0.0) + }; + let mut subscript_shift_down = if character_like_base { + 0.0 + } else { + (base_depth + metrics.subscript_baseline_drop_min).max(0.0) + }; + + if let Some(script) = superscript { + let script_depth = script.height - script.baseline; + let required_shift = if cramped { + metrics.superscript_shift_up_cramped + } else { + metrics.superscript_shift_up + }; + superscript_shift_up = superscript_shift_up + .max(required_shift) + .max(script_depth + metrics.superscript_bottom_min); + } + if let Some(script) = subscript { + subscript_shift_down = subscript_shift_down.max(metrics.subscript_shift_down); + if superscript.is_none() { + subscript_shift_down = + subscript_shift_down.max(script.baseline - metrics.subscript_top_max); + } + } + if let (Some(superscript), Some(subscript)) = (superscript, subscript) { + let superscript_depth = superscript.height - superscript.baseline; + let gap = (superscript_shift_up - superscript_depth) + - (subscript.baseline - subscript_shift_down); + if gap < metrics.sub_superscript_gap_min { + subscript_shift_down += metrics.sub_superscript_gap_min - gap; + } + let superscript_bottom = superscript_shift_up - superscript_depth; + if superscript_bottom < metrics.superscript_bottom_max_with_subscript { + let adjustment = metrics.superscript_bottom_max_with_subscript - superscript_bottom; + superscript_shift_up += adjustment; + subscript_shift_down -= adjustment; + } + } + + let superscript_y = + superscript.map(|script| base.baseline - superscript_shift_up - script.baseline); + let subscript_y = + subscript.map(|script| base.baseline + subscript_shift_down - script.baseline); + let top = superscript_y + .into_iter() + .chain(subscript_y) + .fold(0.0_f64, f64::min); + let bottom = superscript + .zip(superscript_y) + .map(|(script, y)| y + script.height) + .into_iter() + .chain( + subscript + .zip(subscript_y) + .map(|(script, y)| y + script.height), + ) + .fold(base.height, f64::max); + let shift = -top; + + MathScriptLayout { + height: bottom - top, + baseline: base.baseline + shift, + base_y: shift, + superscript_shift_up: superscript.map(|_| superscript_shift_up), + superscript_y: superscript_y.map(|y| y + shift), + subscript_shift_down: subscript.map(|_| subscript_shift_down), + subscript_y: subscript_y.map(|y| y + shift), + } +} + +/// Physical constraints for display-style operator limits. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathLimitLayoutMetrics { + pub upper_gap_min: f64, + pub upper_baseline_rise_min: f64, + pub lower_gap_min: f64, + pub lower_baseline_drop_min: f64, + pub outer_padding: f64, +} + +/// Inputs for placing display limits above and below an operator. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathLimitLayoutInput { + pub base: MathBoxDimensions, + pub upper: Option, + pub lower: Option, + pub upper_italic_correction: f64, + pub operator_skew: f64, + pub metrics: MathLimitLayoutMetrics, +} + +/// Positions and bounds for a display operator with limits. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathLimitLayout { + pub width: f64, + pub height: f64, + pub baseline: f64, + pub base_x: f64, + pub base_y: f64, + pub upper_x: Option, + pub upper_y: Option, + pub lower_x: Option, + pub lower_y: Option, +} + +/// Applies TeX's display-limit gaps, baseline constraints, and operator skew. +pub fn layout_display_limits(input: MathLimitLayoutInput) -> MathLimitLayout { + let MathLimitLayoutInput { + base, + upper, + lower, + upper_italic_correction, + operator_skew, + metrics, + } = input; + let width = base + .width + .max( + upper + .map(|script| script.width + upper_italic_correction) + .unwrap_or(0.0), + ) + .max(lower.map(|script| script.width).unwrap_or(0.0)); + let upper_y = upper.map(|script| { + 0.0_f64 + .min(-metrics.upper_gap_min - script.height) + .min(base.baseline - metrics.upper_baseline_rise_min - script.baseline) + }); + let lower_y = lower.map(|script| { + (base.height + metrics.lower_gap_min) + .max(base.baseline + metrics.lower_baseline_drop_min - script.baseline) + }); + let top = upper_y + .map(|y| y - metrics.outer_padding) + .into_iter() + .chain(lower_y) + .fold(0.0_f64, f64::min); + let bottom = upper + .zip(upper_y) + .map(|(script, y)| y + script.height) + .into_iter() + .chain( + lower + .zip(lower_y) + .map(|(script, y)| y + script.height + metrics.outer_padding), + ) + .fold(base.height, f64::max); + let shift = -top; + + MathLimitLayout { + width, + height: bottom - top, + baseline: base.baseline + shift, + base_x: (width - base.width) / 2.0, + base_y: shift, + upper_x: upper.map(|script| (width - script.width) / 2.0 + operator_skew / 2.0), + upper_y: upper_y.map(|y| y + shift), + lower_x: lower.map(|script| (width - script.width) / 2.0 - operator_skew / 2.0), + lower_y: lower_y.map(|y| y + shift), + } +} + +/// Required height of a radical sign for a radicand and its overbar. +pub fn radical_sign_target_height(content_height: f64, clearance: f64, rule_thickness: f64) -> f64 { + content_height + clearance + rule_thickness +} + +/// Inputs for positioning a radical sign, optional index, radicand, and rule. +/// +/// Values use one consistent coordinate unit chosen by the caller. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathRadicalLayoutInput { + pub content: MathBoxDimensions, + pub index: Option, + pub root_width: f64, + pub root_height: f64, + pub clearance: f64, + pub rule_thickness: f64, + pub extra_ascender: f64, + pub kern_before_degree: f64, + pub kern_after_degree: f64, + pub degree_raise_percent: f64, + pub rule_overlap: f64, +} + +/// Geometry for the radical sign, optional index, radicand, and overbar. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MathRadicalLayout { + pub width: f64, + pub height: f64, + pub baseline: f64, + pub index_x: f64, + pub index_y: Option, + pub root_x: f64, + pub root_y: f64, + pub root_position_y: f64, + pub rule_start_x: f64, + pub rule_y: f64, + pub content_x: f64, + pub content_y: f64, +} + +/// Places a radical and computes the enclosing math box. +pub fn layout_radical_box(input: MathRadicalLayoutInput) -> MathRadicalLayout { + let MathRadicalLayoutInput { + content, + index, + root_width, + root_height, + clearance, + rule_thickness, + extra_ascender, + kern_before_degree, + kern_after_degree, + degree_raise_percent, + rule_overlap, + } = input; + let target_height = radical_sign_target_height(content.height, clearance, rule_thickness); + let radicand_y = extra_ascender + rule_thickness + clearance; + let baseline = radicand_y + content.baseline; + let excess_height = (root_height - target_height).max(0.0); + let root_y = extra_ascender - excess_height / 2.0; + let index_width = index.map(|index| index.width).unwrap_or(0.0); + let root_x = index + .map(|index| (index.width + kern_before_degree + kern_after_degree).max(0.0)) + .unwrap_or(0.0); + let index_y = index.map(|index| baseline - root_height * degree_raise_percent - index.height); + let radical_top = -excess_height / 2.0; + let top = index_y + .map(|index_y| radical_top.min(index_y).min(root_y)) + .unwrap_or_else(|| radical_top.min(root_y)); + let bottom = index + .zip(index_y) + .map(|(index, index_y)| (index_y + index.height).max(radicand_y + content.height)) + .unwrap_or(radicand_y + content.height) + .max(root_y + root_height); + let shift = -top; + let rule_y = root_y + rule_thickness / 2.0 + shift; + + MathRadicalLayout { + width: (root_x + root_width + content.width).max(index_width), + height: bottom - top, + baseline: baseline + shift, + index_x: 0.0, + index_y: index_y.map(|index_y| index_y + shift), + root_x, + root_y, + root_position_y: root_y + shift, + rule_start_x: root_x + root_width - rule_overlap, + rule_y, + content_x: root_x + root_width, + content_y: radicand_y + shift, + } +} diff --git a/crates/texrra-core/src/math_list.rs b/crates/texrra-core/src/math_list.rs new file mode 100644 index 0000000..1669ab2 --- /dev/null +++ b/crates/texrra-core/src/math_list.rs @@ -0,0 +1,403 @@ +use crate::{ + MathClass, MathStyle, MathStyleCommand, + glue::TeXGlue, + math_expr::{MathExpr, MathLineBreakPenalties, MathMuGlue, MathSpacingSettings}, +}; + +/// TeX's inter-atom spacing category for one pair of math classes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MathSpacingKind { + None, + ThinConditional, + Thin, + MediumConditional, + ThickConditional, +} + +/// The first and last math classes contributed by one item in a math list. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct MathBoundary { + pub leading: Option, + pub trailing: Option, +} + +/// Neighboring classes that constrain a nested math list. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct MathListContext { + pub previous: Option, + pub next: Option, +} + +/// One engine-planned item for the application inline-math line breaker. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MathInlineItemPlan<'a> { + Formula { + expression: &'a MathExpr, + math_style: MathStyle, + spacing: MathSpacingSettings, + child_context: MathListContext, + spacing_before: Option, + break_after: Option, + }, + Glue(TeXGlue), + Penalty(i32), +} + +/// Plan the top-level items and break opportunities for an inline math list. +/// +/// The core resolves math styles, mu glue, explicit penalties, and automatic +/// relation/binary break penalties. The caller remains responsible for +/// measuring each formula and converting mu glue for its line-break backend. +pub fn plan_inline_math<'a>( + expression: &'a MathExpr, + math_style: MathStyle, + spacing: MathSpacingSettings, + line_break_penalties: MathLineBreakPenalties, + allow_trailing_break: bool, +) -> Vec> { + if let Some(penalty) = explicit_math_break_penalty(expression) { + return vec![MathInlineItemPlan::Penalty(penalty)]; + } + if let MathExpr::Glue(glue) = expression { + return vec![MathInlineItemPlan::Glue(*glue)]; + } + let MathExpr::Sequence(items) = expression else { + return vec![MathInlineItemPlan::Formula { + expression, + math_style, + spacing, + child_context: MathListContext::default(), + spacing_before: None, + break_after: None, + }]; + }; + + let classes = normalized_classes(items, math_style, MathListContext::default()); + let mut current_math_style = math_style; + let mut current_spacing = spacing; + let mut current_line_break_penalties = line_break_penalties; + let mut previous_class = None; + let mut planned = Vec::with_capacity(items.len()); + + for (index, expression) in items.iter().enumerate() { + if let MathExpr::MathSpacingChange(settings) = expression { + current_spacing = *settings; + continue; + } + if let MathExpr::MathLineBreakPenaltiesChange(penalties) = expression { + current_line_break_penalties = *penalties; + continue; + } + if let Some(penalty) = explicit_math_break_penalty(expression) { + planned.push(MathInlineItemPlan::Penalty(penalty)); + continue; + } + if let MathExpr::Glue(glue) = expression { + planned.push(MathInlineItemPlan::Glue(*glue)); + previous_class = classes[index].trailing.or(previous_class); + continue; + } + + let boundary = classes[index]; + if let Some(command) = math_style_command(expression) { + current_math_style = MathStyle::from_command(command); + continue; + } + + let spacing_before = previous_class + .zip(boundary.leading) + .map(|(previous, next)| { + inter_atom_spacing(previous, next, current_math_style, current_spacing) + }); + let break_after = automatic_math_break_after( + items, + &classes, + index, + boundary, + current_line_break_penalties, + allow_trailing_break, + ); + planned.push(MathInlineItemPlan::Formula { + expression, + math_style: current_math_style, + spacing: current_spacing, + child_context: child_context(&classes, index, MathListContext::default()), + spacing_before, + break_after, + }); + previous_class = boundary.trailing.or(previous_class); + } + + planned +} + +fn automatic_math_break_after( + items: &[MathExpr], + classes: &[MathBoundary], + index: usize, + boundary: MathBoundary, + penalties: MathLineBreakPenalties, + allow_trailing_break: bool, +) -> Option { + let penalty = match boundary.trailing { + Some(MathClass::Relation) => penalties.relation, + Some(MathClass::Binary) => penalties.binary, + _ => return None, + }; + let next_blocks_automatic_break = items + .iter() + .enumerate() + .skip(index + 1) + .find(|(_, item)| !is_math_layout_metadata(item)) + .is_some_and(|(next_index, next)| { + classes[next_index].leading == Some(MathClass::Relation) + || explicit_math_break_penalty(next).is_some() + }); + if (index + 1 < items.len() || allow_trailing_break) + && !next_blocks_automatic_break + && penalty < 10_000 + { + Some(penalty) + } else { + None + } +} + +fn explicit_math_break_penalty(expression: &MathExpr) -> Option { + match expression { + MathExpr::Spanned { expression, .. } => explicit_math_break_penalty(expression), + MathExpr::BreakPenalty(penalty) => Some(*penalty), + _ => None, + } +} + +fn is_math_layout_metadata(expression: &MathExpr) -> bool { + match expression { + MathExpr::Spanned { expression, .. } => is_math_layout_metadata(expression), + MathExpr::MathStyleChange(_) + | MathExpr::MathSpacingChange(_) + | MathExpr::MathLineBreakPenaltiesChange(_) => true, + _ => false, + } +} + +/// Find a style command wrapped only in source metadata. +pub fn math_style_command(expression: &MathExpr) -> Option { + match expression { + MathExpr::Spanned { expression, .. } => math_style_command(expression), + MathExpr::MathStyleChange(command) => Some(*command), + _ => None, + } +} + +/// Select the active `\\mathchoice` branch for a TeX math style. +pub fn math_choice_variant(expression: &MathExpr, math_style: MathStyle) -> &MathExpr { + match expression { + MathExpr::Spanned { expression, .. } => math_choice_variant(expression, math_style), + MathExpr::MathChoice { + display, + text, + script, + scriptscript, + } => math_choice_variant( + match math_style { + MathStyle::Display | MathStyle::DisplayCramped => display, + MathStyle::Text | MathStyle::TextCramped => text, + MathStyle::Script | MathStyle::ScriptCramped => script, + MathStyle::ScriptScript | MathStyle::ScriptScriptCramped => scriptscript, + }, + math_style, + ), + expression => expression, + } +} + +/// Convert a parsed math sequence into class boundaries, including TeX's +/// style-sensitive `\\mathchoice` selection and binary-operator normalization. +pub fn normalized_classes( + items: &[MathExpr], + math_style: MathStyle, + list_context: MathListContext, +) -> Vec { + let mut current_math_style = math_style; + let mut classes = items + .iter() + .map(|item| { + if let Some(command) = math_style_command(item) { + current_math_style = MathStyle::from_command(command); + } + let item = math_choice_variant(item, current_math_style); + MathBoundary { + leading: math_list_leading_class(item, current_math_style), + trailing: math_list_trailing_class(item, current_math_style), + } + }) + .collect::>(); + + normalize_binary_operators(&mut classes, list_context); + classes +} + +/// Get the first visible math class contributed by an expression. +pub fn math_list_leading_class(expression: &MathExpr, math_style: MathStyle) -> Option { + match expression { + MathExpr::Spanned { expression, .. } | MathExpr::Styled { expression, .. } => { + math_list_leading_class(expression, math_style) + } + MathExpr::Sequence(items) => { + let mut current_math_style = math_style; + for item in items { + if let Some(command) = math_style_command(item) { + current_math_style = MathStyle::from_command(command); + } else if let Some(class) = math_list_leading_class(item, current_math_style) { + return Some(class); + } + } + None + } + MathExpr::MathChoice { .. } => { + math_list_leading_class(math_choice_variant(expression, math_style), math_style) + } + MathExpr::MathStyleChange(_) + | MathExpr::Space(_) + | MathExpr::Glue(_) + | MathExpr::Kern(_) => None, + _ => expression.leading_class(), + } +} + +/// Get the last visible math class contributed by an expression. +pub fn math_list_trailing_class(expression: &MathExpr, math_style: MathStyle) -> Option { + match expression { + MathExpr::Spanned { expression, .. } | MathExpr::Styled { expression, .. } => { + math_list_trailing_class(expression, math_style) + } + MathExpr::Sequence(items) => { + let mut current_math_style = math_style; + let mut trailing_class = None; + for item in items { + if let Some(command) = math_style_command(item) { + current_math_style = MathStyle::from_command(command); + } else { + trailing_class = + math_list_trailing_class(item, current_math_style).or(trailing_class); + } + } + trailing_class + } + MathExpr::MathChoice { .. } => { + math_list_trailing_class(math_choice_variant(expression, math_style), math_style) + } + MathExpr::MathStyleChange(_) + | MathExpr::Space(_) + | MathExpr::Glue(_) + | MathExpr::Kern(_) => None, + _ => expression.trailing_class(), + } +} + +/// Resolve TeX's eight-class math spacing table. +pub fn spacing_kind(left: MathClass, right: MathClass) -> MathSpacingKind { + const TABLE: &[u8; 64] = b"0234000122*4000133**3**344*0400400*000000234000111*1111112341011"; + match TABLE[left.index() * 8 + right.index()] { + b'1' => MathSpacingKind::ThinConditional, + b'2' => MathSpacingKind::Thin, + b'3' => MathSpacingKind::MediumConditional, + b'4' => MathSpacingKind::ThickConditional, + _ => MathSpacingKind::None, + } +} + +/// Select the TeX math glue for a class pair and math style. +pub fn inter_atom_spacing( + left: MathClass, + right: MathClass, + math_style: MathStyle, + settings: MathSpacingSettings, +) -> MathMuGlue { + let glue = match spacing_kind(left, right) { + MathSpacingKind::ThinConditional if math_style.conditional_math_spacing() => { + settings.thin.0 + } + MathSpacingKind::Thin => settings.thin.0, + MathSpacingKind::MediumConditional if math_style.conditional_math_spacing() => { + settings.medium.0 + } + MathSpacingKind::ThickConditional if math_style.conditional_math_spacing() => { + settings.thick.0 + } + _ => common::Glue::ZERO, + }; + MathMuGlue(glue) +} + +/// Apply TeX's binary-operator-to-ordinary-atom rule to a math list. +pub fn normalize_binary_operators(boundaries: &mut [MathBoundary], context: MathListContext) { + for index in 0..boundaries.len() { + if boundaries[index].leading != Some(MathClass::Binary) { + continue; + } + + let previous = boundaries[..index] + .iter() + .rev() + .find_map(|boundary| boundary.trailing) + .or(context.previous); + if previous.is_none_or(|class| { + matches!( + class, + MathClass::Binary + | MathClass::Operator + | MathClass::Relation + | MathClass::Opening + | MathClass::Punctuation + ) + }) { + boundaries[index].leading = Some(MathClass::Ordinary); + if boundaries[index].trailing == Some(MathClass::Binary) { + boundaries[index].trailing = Some(MathClass::Ordinary); + } + } + } + + for index in (0..boundaries.len()).rev() { + if boundaries[index].trailing != Some(MathClass::Binary) { + continue; + } + + let next = boundaries[index + 1..] + .iter() + .find_map(|boundary| boundary.leading) + .or(context.next); + if next.is_none_or(|class| { + matches!( + class, + MathClass::Relation | MathClass::Closing | MathClass::Punctuation + ) + }) { + boundaries[index].trailing = Some(MathClass::Ordinary); + if boundaries[index].leading == Some(MathClass::Binary) { + boundaries[index].leading = Some(MathClass::Ordinary); + } + } + } +} + +/// Carry the nearest visible classes across an item into its nested list. +pub fn child_context( + boundaries: &[MathBoundary], + index: usize, + parent: MathListContext, +) -> MathListContext { + MathListContext { + previous: boundaries[..index] + .iter() + .rev() + .find_map(|boundary| boundary.trailing) + .or(parent.previous), + next: boundaries[index + 1..] + .iter() + .find_map(|boundary| boundary.leading) + .or(parent.next), + } +} diff --git a/crates/texrra-core/src/math_lowering.rs b/crates/texrra-core/src/math_lowering.rs new file mode 100644 index 0000000..87d89df --- /dev/null +++ b/crates/texrra-core/src/math_lowering.rs @@ -0,0 +1,1354 @@ +use std::collections::{HashMap, VecDeque}; + +use crate::{ + expanded::{self, ExpandedTokenStream}, + math_code::UnicodeMathCode, + math_expr::*, + math_mode::{ + MathScope as Delimiter, is_display_math_environment, math_delimiter_error, + validate_math_delimiters, + }, + source::{SourceLocation, SourceOrigin}, +}; + +const DEFAULT_JOT: common::Scaled = common::Scaled(3 * 65_536); + +fn default_jot() -> common::Scaled { + DEFAULT_JOT +} + +#[derive(Clone, PartialEq, Eq, Hash)] +struct MathParseCacheKey { + source_segments: Vec, + tokens: Vec, + events: Vec, + delimiter: Delimiter, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +struct MathParseSourceSegmentKey { + output: std::ops::Range, + origin: SourceOrigin, + column_advances: bool, + column_character_starts: Vec, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +struct MathParseTokenKey { + position: usize, + end_position: usize, + value: expanded::ExpandedTokenValue, + math_code: Option, + math_family: Option, + unicode_math_code: Option, + math_fonts: MathFontFamilies, + math_line_break_penalties: MathLineBreakPenalties, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +struct MathParseEventKey { + position: usize, + kind: expanded::FrontendEventKind, + math_line_break_penalties: MathLineBreakPenalties, +} + +#[derive(Clone)] +struct MathParseCacheEntry { + expression: MathExpr, + source_segments: Vec, + events: Vec, +} + +#[derive(Default)] +pub struct MathParseCache { + entries: std::collections::HashMap, + insertion_order: VecDeque, +} + +impl MathParseCache { + fn get( + &self, + key: &MathParseCacheKey, + source_segments: &[expanded::SourceSegment], + events: &[expanded::FrontendEvent], + ) -> Option { + let entry = self.entries.get(key)?; + let locations = rebase_source_locations( + &entry.source_segments, + source_segments, + &entry.events, + events, + &key.tokens, + )?; + let mut expression = entry.expression.clone(); + if !expression.rebase_source_locations(&locations) { + return None; + } + Some(expression) + } + + fn insert( + &mut self, + key: MathParseCacheKey, + expression: MathExpr, + source_segments: Vec, + events: Vec, + ) { + const CAPACITY: usize = 2048; + if !self.entries.contains_key(&key) { + if self.entries.len() == CAPACITY + && let Some(oldest) = self.insertion_order.pop_front() + { + self.entries.remove(&oldest); + } + self.insertion_order.push_back(key.clone()); + } + self.entries.insert( + key, + MathParseCacheEntry { + expression, + source_segments, + events, + }, + ); + } +} + +pub fn lower_math( + source: ExpandedTokenStream, + math_parse_cache: &mut MathParseCache, +) -> Result { + let delimited = convert_math_shift_delimiters(&source)?; + validate_math_delimiters(&delimited)?; + collect_math_expressions(&delimited, math_parse_cache) +} + +fn collect_math_expressions( + source: &expanded::ExpandedTokenStream, + math_parse_cache: &mut MathParseCache, +) -> Result { + use expanded::FrontendEventKind as Event; + + let mut output = expanded::ExpandedTokenStream::default(); + let mut copied_item = 0; + let mut event_item = 0; + let mut active_math: Option<(usize, Delimiter, SourceLocation)> = None; + let mut math_events: Vec = Vec::new(); + + for event in &source.events { + // The event list and the event items are kept in the same order, so the + // next event item belongs to this event. Items before it are the tokens + // that were expanded before the event, including zero-width spaces that + // share the event's byte position. + while event_item < source.items.len() + && !matches!( + source.items[event_item].kind, + expanded::ExpandedItemKind::Event(_) + ) + { + event_item += 1; + } + let this_event_item = event_item; + event_item += 1; + let start_delimiter = match &event.kind { + Event::DisplayMathStart => Some(Delimiter::Display), + Event::InlineMathStart => Some(Delimiter::Inline), + Event::BeginEnvironment { + name: environment, .. + } if is_display_math_environment(environment) => { + Some(Delimiter::Environment(environment.clone())) + } + _ => None, + }; + let end_delimiter = match &event.kind { + Event::DisplayMathEnd(_) => Some(Delimiter::Display), + Event::InlineMathEnd(_) => Some(Delimiter::Inline), + Event::EndEnvironment { name, .. } if is_display_math_environment(name) => { + Some(Delimiter::Environment(name.clone())) + } + _ => None, + }; + + if let Some((content_start, delimiter, location)) = active_math.as_ref() { + if end_delimiter.as_ref() == Some(delimiter) { + if let Some(settings) = math_delimiter_settings_at_scope_end(&event.kind) { + apply_math_delimiter_settings(&mut math_events, settings); + } + let expression = parse_math_for_delimiter( + source, + *content_start..event.position, + &math_events, + delimiter, + math_parse_cache, + )?; + let expression_text = expression.plain_text(); + if !expression_text.is_empty() { + let rows = + equation_rows_for_math(&math_events, delimiter, &expression, location)?; + output.insert_event( + if *delimiter != Delimiter::Inline { + Event::DisplayMath { + expression, + environment: match delimiter { + Delimiter::Environment(name) => Some(name.clone()), + Delimiter::Display | Delimiter::Inline => None, + }, + rows, + } + } else { + Event::InlineMath(expression) + }, + location.clone(), + ); + } + for nested_event in math_events.drain(..) { + if !is_math_structure_event(&nested_event.kind) + && (delimiter == &Delimiter::Inline + || !matches!(&nested_event.kind, Event::Label(_))) + { + output.insert_event(nested_event.kind, nested_event.location); + } + } + active_math = None; + copied_item = this_event_item + 1; + continue; + } + math_events.push(event.clone()); + continue; + } + + output.copy_items(source, &source.items[copied_item..this_event_item]); + copied_item = this_event_item + 1; + if let Some(delimiter) = start_delimiter { + active_math = Some((event.position, delimiter, event.location.clone())); + } else { + output.insert_event(event.kind.clone(), event.location.clone()); + } + } + + if let Some((content_start, delimiter, location)) = active_math { + let expression = parse_math_for_delimiter( + source, + content_start..source.output_len(), + &math_events, + &delimiter, + math_parse_cache, + )?; + if !expression.plain_text().is_empty() { + let rows = equation_rows_for_math(&math_events, &delimiter, &expression, &location)?; + output.insert_event( + if delimiter != Delimiter::Inline { + Event::DisplayMath { + expression, + environment: match &delimiter { + Delimiter::Environment(name) => Some(name.clone()), + Delimiter::Display | Delimiter::Inline => None, + }, + rows, + } + } else { + Event::InlineMath(expression) + }, + location, + ); + } + for nested_event in math_events { + if !is_math_structure_event(&nested_event.kind) + && (delimiter == Delimiter::Inline + || !matches!(&nested_event.kind, Event::Label(_))) + { + output.insert_event(nested_event.kind, nested_event.location); + } + } + copied_item = source.items.len(); + } + + output.copy_items(source, &source.items[copied_item..]); + Ok(output) +} + +fn math_delimiter_settings_at_scope_end( + kind: &expanded::FrontendEventKind, +) -> Option { + use expanded::FrontendEventKind as Event; + + match kind { + Event::DisplayMathEnd(settings) | Event::InlineMathEnd(settings) => Some(*settings), + Event::EndEnvironment { + delimiter_settings, .. + } => Some(*delimiter_settings), + _ => None, + } +} + +fn apply_math_delimiter_settings( + events: &mut [expanded::FrontendEvent], + settings: MathDelimiterSettings, +) { + use expanded::FrontendEventKind as Event; + + for event in events { + match &mut event.kind { + Event::MathDelimiterStart { + settings: event_settings, + .. + } + | Event::MathDelimiterMiddle { + settings: event_settings, + .. + } + | Event::MathDelimiterEnd { + settings: event_settings, + .. + } => *event_settings = settings, + Event::MathManualDelimiter { + settings: event_settings, + .. + } + | Event::MathUnicodeDelimiter { + settings: event_settings, + .. + } => *event_settings = settings, + Event::MathFractionStart { + delimiter_settings, .. + } => *delimiter_settings = settings, + Event::MathInfixFraction(kind, _) => match kind { + MathInfixFractionKind::Choose(event_settings) => *event_settings = settings, + MathInfixFractionKind::OverWithDelims(delimiters) + | MathInfixFractionKind::AtopWithDelims(delimiters) => { + delimiters.settings = settings; + } + MathInfixFractionKind::AboveWithDelims { delimiters, .. } => { + delimiters.settings = settings; + } + MathInfixFractionKind::Over + | MathInfixFractionKind::Atop + | MathInfixFractionKind::Above(_) => {} + }, + _ => {} + } + } +} + +fn is_math_structure_event(kind: &expanded::FrontendEventKind) -> bool { + use expanded::FrontendEventKind as Event; + + matches!( + kind, + Event::MathCell + | Event::RowBreak + | Event::MathFractionStart { .. } + | Event::MathFractionSeparator + | Event::MathFractionEnd + | Event::MathInfixFraction(..) + | Event::MathCharacter { .. } + | Event::MathUnicodeCharacter { .. } + | Event::MathUnicodeDelimiter { .. } + | Event::MathStyleChange(_) + | Event::MathChoiceStart + | Event::MathChoiceBranch(_) + | Event::MathChoiceEnd + | Event::MathLimitMode(_) + | Event::SuppressEquationNumber + | Event::EquationTag(_) + | Event::MathSpace(_) + | Event::HorizontalGlue(_) + | Event::VerticalGlue(_) + | Event::Penalty(_) + | Event::MathAccentStart { .. } + | Event::MathAccentEnd + | Event::MathFontStart(_) + | Event::MathFontEnd + | Event::MathOperatorStart + | Event::MathOperatorEnd + | Event::MathClassStart(_) + | Event::MathClassEnd + | Event::MathRootStart { .. } + | Event::MathRootSeparator + | Event::MathRootEnd + | Event::MathDelimiterStart { .. } + | Event::MathDelimiterMiddle { .. } + | Event::MathDelimiterEnd { .. } + | Event::MathManualDelimiter { .. } + | Event::LiteralAmpersand + | Event::LiteralCharacter(_) + | Event::LineBreak + | Event::GroupStart + | Event::GroupEnd + ) +} + +fn equation_rows_for_math( + events: &[expanded::FrontendEvent], + delimiter: &Delimiter, + expression: &MathExpr, + location: &SourceLocation, +) -> Result, String> { + use expanded::{DisplayMathRow, FrontendEventKind as Event}; + + if matches!(delimiter, Delimiter::Inline) + && events + .iter() + .any(|event| matches!(event.kind, Event::EquationTag(_))) + { + return Err(math_delimiter_error( + location, + "`\\tag` can only be used in display math", + )); + } + + let has_alignment_rows = matches!( + delimiter, + Delimiter::Environment(name) + if matches!( + name.as_str(), + "align" | "align*" | "alignat" | "alignat*" | "flalign" | "flalign*" + | "eqnarray" | "eqnarray*" | "gather" | "gather*" + ) + ); + let mut rows = vec![DisplayMathRow::default()]; + let mut nested_environment_depth = 0usize; + for event in events { + match &event.kind { + Event::BeginEnvironment { .. } => nested_environment_depth += 1, + Event::EndEnvironment { .. } => { + nested_environment_depth = nested_environment_depth.saturating_sub(1); + } + Event::RowBreak if has_alignment_rows && nested_environment_depth == 0 => { + rows.push(DisplayMathRow::default()); + } + Event::EquationTag(tag) => { + let row = rows.last_mut().expect("display math has at least one row"); + if row.equation_tag.replace(tag.clone()).is_some() { + return Err(math_delimiter_error( + &event.location, + "only one `\\tag` is allowed per displayed equation row", + )); + } + } + Event::SuppressEquationNumber => { + rows.last_mut() + .expect("display math has at least one row") + .suppress_number = true; + } + Event::Label(key) => rows + .last_mut() + .expect("display math has at least one row") + .labels + .push(key.clone()), + _ => {} + } + } + + if has_alignment_rows && let Some(row_count) = equation_alignment_row_count(expression) { + rows.truncate(row_count); + rows.resize_with(row_count, DisplayMathRow::default); + } + + Ok(rows) +} + +fn equation_alignment_row_count(expression: &MathExpr) -> Option { + match expression { + MathExpr::Spanned { expression, .. } + | MathExpr::Styled { expression, .. } + | MathExpr::Classified { + body: expression, .. + } => equation_alignment_row_count(expression), + MathExpr::Sequence(items) if items.len() == 1 => equation_alignment_row_count(&items[0]), + MathExpr::Alignment { rows, .. } => Some(rows.len()), + _ => None, + } +} + +fn parse_math_for_delimiter( + source: &expanded::ExpandedTokenStream, + range: std::ops::Range, + events: &[expanded::FrontendEvent], + delimiter: &Delimiter, + math_parse_cache: &mut MathParseCache, +) -> Result { + let source_segments = source.segment_signature(range.clone()); + let math_events = events + .iter() + .filter(|event| range.start <= event.position && event.position <= range.end) + .cloned() + .collect::>(); + let math_tokens = source + .items + .iter() + .filter(|item| range.start <= item.position && item.position < range.end) + .filter_map(|item| match &item.kind { + expanded::ExpandedItemKind::Token(value) => Some(MathParseTokenKey { + position: item.position - range.start, + end_position: item.end_position - range.start, + value: value.clone(), + math_code: item.math_code, + math_family: item.math_family, + unicode_math_code: item.unicode_math_code, + math_fonts: std::sync::Arc::clone(&item.math_fonts), + math_line_break_penalties: item.math_line_break_penalties, + }), + expanded::ExpandedItemKind::Event(_) => None, + }) + .collect(); + let key = MathParseCacheKey { + source_segments: source_segments + .iter() + .map(|segment| MathParseSourceSegmentKey { + output: segment.output.clone(), + origin: segment.location.origin.clone(), + column_advances: segment.column_advances, + column_character_starts: segment.column_character_starts.clone(), + }) + .collect(), + tokens: math_tokens, + events: math_events + .iter() + .map(|event| MathParseEventKey { + position: event.position - range.start, + kind: event.kind.clone(), + math_line_break_penalties: event.math_line_break_penalties, + }) + .collect(), + delimiter: delimiter.clone(), + }; + if let Some(expression) = math_parse_cache.get(&key, &source_segments, &math_events) { + return Ok(expression); + } + + let expression = if let Delimiter::Environment(environment) = delimiter { + let (body_start, alignment) = math_environment_preamble(range.clone(), environment, events); + let (math_fonts, jot) = events + .iter() + .find_map(|event| { + if range.start <= event.position && event.position <= range.end { + match &event.kind { + expanded::FrontendEventKind::BeginEnvironment { + name, + math_fonts, + jot, + } if name == environment => Some((math_fonts.clone(), *jot)), + _ => None, + } + } else { + None + } + }) + .unwrap_or_else(|| (MathFontFamilies::default(), default_jot())); + let expression = parse_math_with_environments(source, body_start..range.end, events)?; + apply_math_environment_with_alignment(expression, environment, alignment, math_fonts, jot) + } else { + parse_math_with_environments(source, range, events)? + }; + math_parse_cache.insert(key, expression.clone(), source_segments, math_events); + Ok(expression) +} + +fn rebase_source_locations( + old_segments: &[expanded::SourceSegment], + new_segments: &[expanded::SourceSegment], + old_events: &[expanded::FrontendEvent], + new_events: &[expanded::FrontendEvent], + tokens: &[MathParseTokenKey], +) -> Option> { + if old_segments.len() != new_segments.len() || old_events.len() != new_events.len() { + return None; + } + + let mut locations = HashMap::new(); + for (old, new) in old_segments.iter().zip(new_segments) { + if old.output != new.output + || old.column_advances != new.column_advances + || old.location.origin != new.location.origin + { + return None; + } + + if old.column_advances { + let character_count = token_character_count(tokens, &old.output)?; + let mut old_location = old.location.clone(); + let mut new_location = new.location.clone(); + if !insert_location_mapping(&mut locations, old_location.clone(), new_location.clone()) + { + return None; + } + for _ in 0..character_count { + old_location.column += 1; + new_location.column += 1; + if !insert_location_mapping( + &mut locations, + old_location.clone(), + new_location.clone(), + ) { + return None; + } + } + } else if !insert_location_mapping( + &mut locations, + old.location.clone(), + new.location.clone(), + ) { + return None; + } + } + + for (old, new) in old_events.iter().zip(new_events) { + if old.kind != new.kind + || old.math_line_break_penalties != new.math_line_break_penalties + || !insert_location_mapping(&mut locations, old.location.clone(), new.location.clone()) + { + return None; + } + } + + Some(locations) +} + +fn token_character_count( + tokens: &[MathParseTokenKey], + range: &std::ops::Range, +) -> Option { + let count = tokens + .iter() + .filter(|token| range.start <= token.position && token.position < range.end) + .try_fold(0, |count, token| token.value.character().map(|_| count + 1))?; + (count > 0).then_some(count) +} + +fn insert_location_mapping( + locations: &mut HashMap, + old: SourceLocation, + new: SourceLocation, +) -> bool { + match locations.get(&old) { + Some(previous) => previous == &new, + None => { + locations.insert(old, new); + true + } + } +} + +fn parse_math_with_environments( + source: &expanded::ExpandedTokenStream, + range: std::ops::Range, + events: &[expanded::FrontendEvent], +) -> Result { + use expanded::FrontendEventKind as Event; + + let Some((begin_index, end_index, environment, math_fonts, jot)) = + events.iter().enumerate().find_map(|(begin_index, event)| { + let Event::BeginEnvironment { + name: environment, + math_fonts, + jot, + } = &event.kind + else { + return None; + }; + if event.position < range.start + || event.position >= range.end + || !is_nested_math_environment(environment) + { + return None; + } + + let mut depth = 0usize; + let end_index = + events + .iter() + .enumerate() + .skip(begin_index) + .find_map(|(index, candidate)| match &candidate.kind { + Event::BeginEnvironment { name, .. } if name == environment => { + depth += 1; + None + } + Event::EndEnvironment { name, .. } if name == environment => { + depth -= 1; + (depth == 0).then_some(index) + } + _ => None, + })?; + Some(( + begin_index, + end_index, + environment.clone(), + math_fonts.clone(), + *jot, + )) + }) + else { + return parse_math_rows(source, range, events); + }; + + let begin_position = events[begin_index].position; + let end_position = events[end_index].position; + let (body_start, alignment) = + math_environment_preamble(begin_position..end_position, &environment, events); + let mut expressions = Vec::with_capacity(3); + if range.start < begin_position { + let prefix = parse_math_with_environments( + source, + range.start..begin_position, + &events[..begin_index], + )?; + if !prefix.plain_text().is_empty() { + expressions.push(prefix); + } + } + + let body = parse_math_with_environments( + source, + body_start..end_position, + &events[begin_index + 1..end_index], + )?; + expressions.push(apply_math_environment_with_alignment( + body, + &environment, + alignment, + math_fonts, + jot, + )); + + if end_position < range.end { + let suffix = parse_math_with_environments( + source, + end_position..range.end, + &events[end_index + 1..], + )?; + if !suffix.plain_text().is_empty() { + expressions.push(suffix); + } + } + + Ok(match expressions.len() { + 1 => expressions.pop().unwrap(), + _ => MathExpr::Sequence(expressions), + }) +} + +fn parse_math_rows( + source: &expanded::ExpandedTokenStream, + range: std::ops::Range, + events: &[expanded::FrontendEvent], +) -> Result { + use expanded::FrontendEventKind as Event; + + let row_breaks = events + .iter() + .enumerate() + .filter(|(_, event)| { + matches!(&event.kind, Event::RowBreak) + && range.start <= event.position + && event.position < range.end + }) + .collect::>(); + let mut rows = Vec::with_capacity(row_breaks.len() + 1); + let mut row_start = range.start; + let mut event_start = 0; + for (break_index, row_break) in row_breaks { + rows.push(parse_math_row( + source, + row_start..row_break.position, + &events[event_start..break_index], + )?); + row_start = row_break.position; + event_start = break_index + 1; + } + if row_start < range.end || rows.is_empty() { + rows.push(parse_math_row( + source, + row_start..range.end, + &events[event_start..], + )?); + } + + if rows.len() == 1 && rows[0].len() == 1 { + return Ok(rows.pop().unwrap().pop().unwrap()); + } + + Ok(MathExpr::Spanned { + location: source.source_at(range.start), + expression: Box::new(MathExpr::Alignment { + rows, + alignment: MathAlignment::Alternating, + baseline: MathAlignmentBaseline::FirstRow, + math_fonts: MathFontFamilies::default(), + cell_style: MathCellStyle::Inherit, + row_spacing: MathRowSpacing::Array, + }), + }) +} + +fn parse_math_row( + source: &expanded::ExpandedTokenStream, + range: std::ops::Range, + events: &[expanded::FrontendEvent], +) -> Result, String> { + let cell_positions = events + .iter() + .filter_map(|event| { + (matches!(&event.kind, expanded::FrontendEventKind::MathCell) + && range.start <= event.position + && event.position <= range.end) + .then_some(event.position - range.start) + }) + .collect::>(); + if let Some(cells) = + crate::math_parser::split_math_cells(source, range.clone(), &cell_positions) + { + return cells + .into_iter() + .map(|cell| { + let child_range = range.start + cell.start..range.start + cell.end; + let child_events = events + .iter() + .filter(|event| { + child_range.start <= event.position && event.position <= child_range.end + }) + .cloned() + .collect::>(); + crate::math_parser::parse_math_expression_with_events( + source, + child_range, + &child_events, + ) + }) + .collect(); + } + Ok(vec![crate::math_parser::parse_math_expression_with_events( + source, range, events, + )?]) +} + +fn is_nested_math_environment(environment: &str) -> bool { + matches!( + environment, + "matrix" + | "pmatrix" + | "bmatrix" + | "Bmatrix" + | "vmatrix" + | "Vmatrix" + | "smallmatrix" + | "aligned" + | "alignedat" + | "split" + | "gathered" + | "array" + | "cases" + ) +} + +fn math_environment_preamble( + range: std::ops::Range, + environment: &str, + events: &[expanded::FrontendEvent], +) -> (usize, MathAlignment) { + let default_alignment = match environment { + "matrix" | "pmatrix" | "bmatrix" | "Bmatrix" | "vmatrix" | "Vmatrix" | "smallmatrix" + | "gather" | "gather*" | "gathered" => MathAlignment::Centered, + "multline" | "multline*" => MathAlignment::Multline, + "cases" => MathAlignment::Left, + "alignedat" | "alignat" | "alignat*" => MathAlignment::AlternatingTight, + "eqnarray" | "eqnarray*" => MathAlignment::Columns(vec![ + MathColumnAlignment::Right, + MathColumnAlignment::Center, + MathColumnAlignment::Left, + ]), + _ => MathAlignment::Alternating, + }; + if !matches!(environment, "array" | "alignedat" | "alignat" | "alignat*") { + return (range.start, default_alignment); + } + + let argument = events.iter().find_map(|event| { + (event.position == range.start) + .then_some(&event.kind) + .and_then(|kind| match kind { + expanded::FrontendEventKind::EnvironmentArgument(argument) => { + Some(argument.as_str()) + } + _ => None, + }) + }); + let alignment = if environment == "array" { + argument + .and_then(parse_array_preamble) + .map(|(columns, vertical_rules)| MathAlignment::ArrayColumns { + columns, + vertical_rules, + }) + .unwrap_or(default_alignment) + } else { + default_alignment + }; + (range.start, alignment) +} + +fn parse_array_preamble(preamble: &str) -> Option<(Vec, Vec)> { + let mut columns = Vec::new(); + let mut vertical_rules = vec![0]; + parse_array_preamble_part(preamble, &mut columns, &mut vertical_rules, 0)?; + (!columns.is_empty()).then_some((columns, vertical_rules)) +} + +fn parse_array_preamble_part( + preamble: &str, + columns: &mut Vec, + vertical_rules: &mut Vec, + depth: usize, +) -> Option<()> { + const MAX_ARRAY_COLUMNS: usize = 256; + const MAX_PREAMBLE_DEPTH: usize = 16; + + if depth > MAX_PREAMBLE_DEPTH { + return None; + } + + let mut cursor = 0; + + while cursor < preamble.len() { + cursor = skip_space_and_comments(preamble, cursor); + if cursor >= preamble.len() { + break; + } + let character = preamble[cursor..].chars().next()?; + let next = cursor + character.len_utf8(); + match character { + 'l' | 'c' | 'r' => { + if columns.len() >= MAX_ARRAY_COLUMNS { + return None; + } + columns.push(match character { + 'l' => MathColumnAlignment::Left, + 'c' => MathColumnAlignment::Center, + 'r' => MathColumnAlignment::Right, + _ => unreachable!(), + }); + vertical_rules.push(0); + cursor = next; + } + '|' => { + if let Some(rule_count) = vertical_rules.last_mut() { + *rule_count += 1; + } + cursor = next; + } + '*' => { + let count_start = skip_space_and_comments(preamble, next); + let Some((count, after_count)) = read_braced_group(preamble, count_start) else { + cursor = next; + continue; + }; + let Ok(repetitions) = count.trim().parse::() else { + return None; + }; + let pattern_start = skip_space_and_comments(preamble, after_count); + let Some((pattern, after_pattern)) = read_braced_group(preamble, pattern_start) + else { + cursor = next; + continue; + }; + if repetitions > MAX_ARRAY_COLUMNS { + return None; + } + for _ in 0..repetitions { + parse_array_preamble_part(pattern, columns, vertical_rules, depth + 1)?; + } + cursor = after_pattern; + } + '@' | 'p' | 'm' | 'b' | '>' | '<' | '!' => { + let group_start = skip_space_and_comments(preamble, next); + if preamble[group_start..].starts_with('{') + && let Some((_, after_group)) = read_braced_group(preamble, group_start) + { + cursor = after_group; + } else { + cursor = next; + } + } + _ => cursor = next, + } + } + + Some(()) +} + +fn apply_math_environment_with_alignment( + expression: MathExpr, + environment: &str, + alignment: MathAlignment, + math_fonts: MathFontFamilies, + jot: common::Scaled, +) -> MathExpr { + let force_alignment = matches!( + environment, + "matrix" + | "pmatrix" + | "bmatrix" + | "Bmatrix" + | "vmatrix" + | "Vmatrix" + | "smallmatrix" + | "aligned" + | "alignedat" + | "split" + | "gathered" + | "array" + | "cases" + ); + let expression = if force_alignment || is_display_alignment_environment(environment) { + set_math_alignment( + expression, + alignment, + math_alignment_baseline_for_environment(environment), + math_fonts, + math_cell_style_for_environment(environment), + math_row_spacing_for_environment(environment, jot), + force_alignment, + ) + } else { + expression + }; + let (left, right) = match environment { + "pmatrix" => Some(("(", ")")), + "bmatrix" => Some(("[", "]")), + "Bmatrix" => Some(("{", "}")), + "vmatrix" => Some(("|", "|")), + "Vmatrix" => Some(("‖", "‖")), + "cases" => Some(("{", "")), + _ => None, + } + .unwrap_or(("", "")); + if left.is_empty() && right.is_empty() { + expression + } else { + MathExpr::Delimited { + left: MathDelimiterGlyph::plain(left), + body: Box::new(expression), + right: MathDelimiterGlyph::plain(right), + left_settings: MathDelimiterSettings::default(), + right_settings: MathDelimiterSettings::default(), + } + } +} + +fn set_math_alignment( + expression: MathExpr, + alignment: MathAlignment, + baseline: MathAlignmentBaseline, + math_fonts: MathFontFamilies, + cell_style: MathCellStyle, + row_spacing: MathRowSpacing, + force_alignment: bool, +) -> MathExpr { + match expression { + MathExpr::Spanned { + location, + expression, + } => MathExpr::Spanned { + location, + expression: Box::new(set_math_alignment( + *expression, + alignment, + baseline, + math_fonts.clone(), + cell_style, + row_spacing, + force_alignment, + )), + }, + MathExpr::Alignment { + baseline: MathAlignmentBaseline::MathAxisCentered, + .. + } if !force_alignment => expression, + MathExpr::Alignment { rows, .. } => MathExpr::Alignment { + rows, + alignment, + baseline, + math_fonts, + cell_style, + row_spacing, + }, + expression if force_alignment => MathExpr::Alignment { + rows: vec![vec![expression]], + alignment, + baseline, + math_fonts, + cell_style, + row_spacing, + }, + expression => expression, + } +} + +fn is_display_alignment_environment(environment: &str) -> bool { + matches!( + environment, + "align" + | "align*" + | "alignat" + | "alignat*" + | "flalign" + | "flalign*" + | "eqnarray" + | "eqnarray*" + | "gather" + | "gather*" + | "multline" + | "multline*" + ) +} + +fn math_alignment_baseline_for_environment(environment: &str) -> MathAlignmentBaseline { + match environment { + "matrix" | "pmatrix" | "bmatrix" | "Bmatrix" | "vmatrix" | "Vmatrix" | "smallmatrix" + | "aligned" | "alignedat" | "alignedat*" | "split" | "gathered" | "array" | "cases" => { + MathAlignmentBaseline::MathAxisCentered + } + _ => MathAlignmentBaseline::FirstRow, + } +} + +fn math_cell_style_for_environment(environment: &str) -> MathCellStyle { + match environment { + "matrix" | "pmatrix" | "bmatrix" | "Bmatrix" | "vmatrix" | "Vmatrix" | "array" + | "cases" => MathCellStyle::Text, + "smallmatrix" => MathCellStyle::Script, + "aligned" | "alignedat" | "alignedat*" | "split" | "gathered" | "align" | "align*" + | "alignat" | "alignat*" | "flalign" | "flalign*" | "eqnarray" | "eqnarray*" | "gather" + | "gather*" | "multline" | "multline*" => MathCellStyle::Display, + _ => MathCellStyle::Inherit, + } +} + +fn math_row_spacing_for_environment(environment: &str, jot: common::Scaled) -> MathRowSpacing { + match environment { + "cases" => MathRowSpacing::Cases, + "aligned" | "alignedat" | "alignedat*" | "split" | "gathered" | "align" | "align*" + | "alignat" | "alignat*" | "flalign" | "flalign*" | "eqnarray" | "eqnarray*" | "gather" + | "gather*" | "multline" | "multline*" => MathRowSpacing::Equation(jot), + _ => MathRowSpacing::Array, + } +} + +#[derive(Clone, Copy)] +enum DollarMathMode { + Inline, + Display, +} + +struct ActiveDollarMath { + mode: DollarMathMode, + opened_at: SourceLocation, +} + +fn convert_math_shift_delimiters( + source: &expanded::ExpandedTokenStream, +) -> Result { + let mut output = expanded::ExpandedTokenStream::default(); + let mut copied_item = 0; + let mut search_item = 0; + let mut active_math: Option = None; + + while let Some(shift_index) = source.items[search_item..] + .iter() + .position(is_math_shift_item) + .map(|offset| search_item + offset) + { + let item = &source.items[shift_index]; + output.copy_items(source, &source.items[copied_item..shift_index]); + let location = math_shift_location(source, item.position); + let pair_end = math_shift_pair_at(source, item.position); + let mut cursor = item.end_position; + + match active_math.take() { + None => { + if let Some(pair_end) = pair_end { + output.insert_event( + expanded::FrontendEventKind::DisplayMathStart, + location.clone(), + ); + cursor = pair_end; + active_math = Some(ActiveDollarMath { + mode: DollarMathMode::Display, + opened_at: location, + }); + } else { + output.insert_event( + expanded::FrontendEventKind::InlineMathStart, + location.clone(), + ); + active_math = Some(ActiveDollarMath { + mode: DollarMathMode::Inline, + opened_at: location, + }); + } + } + Some(active) => match active.mode { + DollarMathMode::Inline => { + output.insert_event( + expanded::FrontendEventKind::InlineMathEnd(math_delimiter_settings( + source, + item.position, + )), + active.opened_at, + ); + } + DollarMathMode::Display => { + let Some(pair_end) = pair_end else { + return Err(math_delimiter_error( + &location, + "display math should end with `$$`", + )); + }; + output.insert_event( + expanded::FrontendEventKind::DisplayMathEnd(math_delimiter_settings( + source, + item.position, + )), + active.opened_at, + ); + cursor = pair_end; + } + }, + } + + copied_item = source.items.partition_point(|item| item.position < cursor); + search_item = copied_item; + } + + if let Some(active) = active_math { + let expected = math_shift_delimiter_name(active.mode); + return Err(math_delimiter_error( + &active.opened_at, + &format!("math mode opened with `{expected}` has no matching closer"), + )); + } + + output.copy_items(source, &source.items[copied_item..]); + Ok(output) +} + +fn math_delimiter_settings( + source: &expanded::ExpandedTokenStream, + position: usize, +) -> MathDelimiterSettings { + let start = source + .items + .partition_point(|item| item.position < position); + source.items[start..] + .iter() + .take_while(|item| item.position == position) + .find(|item| is_math_shift_item(item)) + .and_then(|item| item.delimiter_settings) + .unwrap_or_default() +} + +fn math_shift_location(source: &expanded::ExpandedTokenStream, position: usize) -> SourceLocation { + source.source_at(position).unwrap_or(SourceLocation { + origin: SourceOrigin::Terminal, + line: 1, + column: 1, + }) +} + +fn math_shift_delimiter_name(mode: DollarMathMode) -> &'static str { + match mode { + DollarMathMode::Inline => "$", + DollarMathMode::Display => "$$", + } +} + +fn math_shift_pair_at(source: &expanded::ExpandedTokenStream, position: usize) -> Option { + let first = math_shift_item_at(source, position)?; + let second = math_shift_item_at(source, first.end_position)?; + Some(second.end_position) +} + +fn math_shift_item_at( + source: &expanded::ExpandedTokenStream, + position: usize, +) -> Option<&expanded::ExpandedItem> { + let start = source + .items + .partition_point(|item| item.position < position); + source.items[start..] + .iter() + .take_while(|item| item.position == position) + .find(|item| is_math_shift_item(item)) +} + +fn is_math_shift_item(item: &expanded::ExpandedItem) -> bool { + matches!( + &item.kind, + expanded::ExpandedItemKind::Token(expanded::ExpandedTokenValue::MathShift(_)) + ) +} +fn skip_space_and_comments(source: &str, mut index: usize) -> usize { + loop { + while source + .as_bytes() + .get(index) + .is_some_and(|byte| byte.is_ascii_whitespace()) + { + index += 1; + } + if source.as_bytes().get(index) != Some(&b'%') { + return index; + } + index = source[index..] + .find('\n') + .map(|offset| index + offset + 1) + .unwrap_or(source.len()); + } +} + +fn read_braced_group(source: &str, index: usize) -> Option<(&str, usize)> { + read_delimited_group(source, index, b'{', b'}') +} + +fn read_delimited_group(source: &str, index: usize, open: u8, close: u8) -> Option<(&str, usize)> { + let bytes = source.as_bytes(); + if bytes.get(index) != Some(&open) { + return None; + } + let mut depth = 1usize; + let mut cursor = index + 1; + while cursor < bytes.len() { + match bytes[cursor] { + b'\\' => { + cursor += 1; + if cursor < bytes.len() { + let character = source[cursor..].chars().next()?; + cursor += character.len_utf8(); + } + } + b'%' => { + cursor = source[cursor..] + .find('\n') + .map(|offset| cursor + offset + 1) + .unwrap_or(source.len()); + } + byte if byte == open => { + depth += 1; + cursor += 1; + } + byte if byte == close => { + depth -= 1; + if depth == 0 { + return Some((&source[index + 1..cursor], cursor + 1)); + } + cursor += 1; + } + _ => { + let character = source[cursor..].chars().next()?; + cursor += character.len_utf8(); + } + } + } + None +} diff --git a/crates/texrra-core/src/math_mode.rs b/crates/texrra-core/src/math_mode.rs new file mode 100644 index 0000000..413157e --- /dev/null +++ b/crates/texrra-core/src/math_mode.rs @@ -0,0 +1,344 @@ +use crate::{ + expanded::{ExpandedTokenStream, FrontendEventKind}, + math_expr::MathInfixFractionKind, + source::{SourceLocation, SourceOrigin}, +}; + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum MathScope { + Display, + Inline, + Environment(String), +} + +impl MathScope { + pub fn from_start_event(kind: &FrontendEventKind) -> Option { + match kind { + FrontendEventKind::DisplayMathStart => Some(Self::Display), + FrontendEventKind::InlineMathStart => Some(Self::Inline), + FrontendEventKind::BeginEnvironment { name, .. } + if is_display_math_environment(name) => + { + Some(Self::Environment(name.clone())) + } + _ => None, + } + } + + pub fn from_end_event(kind: &FrontendEventKind) -> Option { + match kind { + FrontendEventKind::DisplayMathEnd(_) => Some(Self::Display), + FrontendEventKind::InlineMathEnd(_) => Some(Self::Inline), + FrontendEventKind::EndEnvironment { name, .. } if is_display_math_environment(name) => { + Some(Self::Environment(name.clone())) + } + _ => None, + } + } + + fn is_display(&self) -> bool { + !matches!(self, Self::Inline) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum TeXMode { + Vertical, + Horizontal, + InlineMath, + DisplayMath, +} + +pub struct TeXModeState { + mode: TeXMode, + math_scope: Option, + math_opened_at: Option, +} + +impl Default for TeXModeState { + fn default() -> Self { + Self { + mode: TeXMode::Vertical, + math_scope: None, + math_opened_at: None, + } + } +} + +impl TeXModeState { + pub fn enter_math(&mut self, scope: MathScope, location: SourceLocation) { + self.mode = if scope.is_display() { + TeXMode::DisplayMath + } else { + TeXMode::InlineMath + }; + self.math_scope = Some(scope); + self.math_opened_at = Some(location); + } + + pub fn leave_math(&mut self) { + self.mode = match self.mode { + TeXMode::InlineMath => TeXMode::Horizontal, + TeXMode::DisplayMath => TeXMode::Vertical, + TeXMode::Vertical | TeXMode::Horizontal => self.mode, + }; + self.math_scope = None; + self.math_opened_at = None; + } + + pub fn is_math(&self) -> bool { + matches!(self.mode, TeXMode::InlineMath | TeXMode::DisplayMath) + } + + pub fn is_display_math(&self) -> bool { + self.mode == TeXMode::DisplayMath + } + + pub fn math_scope(&self) -> Option<&MathScope> { + self.math_scope.as_ref() + } + + pub fn math_opened_at(&self) -> Option<&SourceLocation> { + self.math_opened_at.as_ref() + } +} + +pub fn is_display_math_environment(environment: &str) -> bool { + matches!( + environment, + "equation" + | "equation*" + | "align" + | "align*" + | "alignat" + | "alignat*" + | "flalign" + | "flalign*" + | "eqnarray" + | "eqnarray*" + | "gather" + | "gather*" + | "multline" + | "multline*" + | "displaymath" + ) +} + +type Delimiter = MathScope; + +pub fn validate_math_delimiters(source: &ExpandedTokenStream) -> Result<(), String> { + use FrontendEventKind as Event; + + let mut mode = TeXModeState::default(); + let mut active_math: Option<(Vec, Vec)> = None; + for event in &source.events { + if mode.is_math() { + let (left_delimiters, fraction_scopes) = active_math + .as_mut() + .expect("active math mode has its delimiter validation state"); + if Delimiter::from_end_event(&event.kind).as_ref() == mode.math_scope() { + if let Some(location) = left_delimiters.last() { + return Err(math_delimiter_error( + location, + "missing `\\right` for this `\\left`", + )); + } + mode.leave_math(); + active_math = None; + continue; + } + if Delimiter::from_end_event(&event.kind).is_some() { + return Err(math_delimiter_error( + mode.math_opened_at().unwrap_or(&event.location), + "the math-mode closing delimiter does not match its opening delimiter", + )); + } + if Delimiter::from_start_event(&event.kind).is_some() { + return Err(math_delimiter_error( + &event.location, + "math mode cannot be started inside math mode", + )); + } + if matches!(event.kind, Event::ParagraphBreak) { + return Err(math_delimiter_error( + &event.location, + "`\\par` is not allowed in math mode", + )); + } + if matches!(event.kind, Event::VerticalGlue(_)) { + return Err(math_delimiter_error( + &event.location, + "vertical glue is not allowed in math mode", + )); + } + if matches!(event.kind, Event::EquationTag(_)) && !mode.is_display_math() { + return Err(math_delimiter_error( + &event.location, + "`\\tag` must appear inside display math", + )); + } + + match &event.kind { + Event::MathDelimiterStart { .. } => { + left_delimiters.push(event.location.clone()); + fraction_scopes.push(0); + } + Event::MathDelimiterMiddle { .. } if left_delimiters.is_empty() => { + return Err(math_delimiter_error( + &event.location, + "`\\middle` must appear between `\\left` and `\\right`", + )); + } + Event::MathDelimiterEnd { .. } if left_delimiters.is_empty() => { + return Err(math_delimiter_error( + &event.location, + "`\\right` has no matching `\\left`", + )); + } + Event::MathDelimiterEnd { .. } => { + left_delimiters.pop(); + if fraction_scopes.len() > 1 { + fraction_scopes.pop(); + } + } + Event::MathManualDelimiter { .. } => {} + Event::MathUnicodeDelimiter { .. } => {} + _ => {} + } + + match &event.kind { + Event::MathInfixFraction(..) => { + let count = fraction_scopes + .last_mut() + .expect("math scope always has a fraction counter"); + *count += 1; + if *count > 1 { + return Err(math_delimiter_error( + &event.location, + "Ambiguous; you need another `{` and `}`", + )); + } + } + Event::GroupStart + | Event::MathFractionStart { .. } + | Event::MathRootStart { .. } + | Event::MathAccentStart { .. } + | Event::MathFontStart(_) + | Event::MathOperatorStart + | Event::MathClassStart(_) => fraction_scopes.push(0), + Event::GroupEnd + | Event::MathFractionEnd + | Event::MathRootEnd + | Event::MathAccentEnd + | Event::MathFontEnd + | Event::MathOperatorEnd + | Event::MathClassEnd => { + if fraction_scopes.len() > 1 { + fraction_scopes.pop(); + } + } + Event::MathFractionSeparator | Event::MathRootSeparator => { + *fraction_scopes + .last_mut() + .expect("math scope always has a fraction counter") = 0; + } + Event::MathCell | Event::RowBreak => { + *fraction_scopes + .last_mut() + .expect("math scope always has a fraction counter") = 0; + } + Event::MathChoiceStart => fraction_scopes.push(0), + Event::MathChoiceBranch(_) => { + *fraction_scopes + .last_mut() + .expect("math scope always has a fraction counter") = 0; + } + Event::MathChoiceEnd => { + if fraction_scopes.len() > 1 { + fraction_scopes.pop(); + } + } + _ => {} + } + continue; + } + + if Delimiter::from_end_event(&event.kind).is_some() { + return Err(math_delimiter_error( + &event.location, + "math-mode closing delimiter has no matching opening delimiter", + )); + } + + if let Some(scope) = Delimiter::from_start_event(&event.kind) { + mode.enter_math(scope, event.location.clone()); + active_math = Some((Vec::new(), vec![0])); + continue; + } + + let message = match &event.kind { + Event::MathDelimiterStart { .. } => Some("`\\left` must appear inside math mode"), + Event::MathDelimiterMiddle { .. } => { + Some("`\\middle` must appear between `\\left` and `\\right`") + } + Event::MathDelimiterEnd { .. } => Some("`\\right` has no matching `\\left`"), + Event::MathInfixFraction(kind, _) => Some(match kind { + MathInfixFractionKind::Over => "`\\over` must appear inside math mode", + MathInfixFractionKind::Atop => "`\\atop` must appear inside math mode", + MathInfixFractionKind::Choose(_) => "`\\choose` must appear inside math mode", + MathInfixFractionKind::Above(_) => "`\\above` must appear inside math mode", + MathInfixFractionKind::OverWithDelims(_) => { + "`\\overwithdelims` must appear inside math mode" + } + MathInfixFractionKind::AtopWithDelims(_) => { + "`\\atopwithdelims` must appear inside math mode" + } + MathInfixFractionKind::AboveWithDelims { .. } => { + "`\\abovewithdelims` must appear inside math mode" + } + }), + Event::MathManualDelimiter { .. } => { + Some("manual delimiter size commands must appear inside math mode") + } + Event::MathCharacter { .. } | Event::MathUnicodeCharacter { .. } => { + Some("math characters must appear inside math mode") + } + Event::MathUnicodeDelimiter { .. } => { + Some("Unicode math delimiters must appear inside math mode") + } + Event::MathStyleChange(_) => Some("math style commands must appear inside math mode"), + Event::MathChoiceStart | Event::MathChoiceBranch(_) | Event::MathChoiceEnd => { + Some("\\mathchoice must appear inside math mode") + } + Event::EquationTag(_) => Some("`\\tag` must appear inside display math"), + _ => None, + }; + if let Some(message) = message { + return Err(math_delimiter_error(&event.location, message)); + } + } + + if let Some((left_delimiters, _)) = active_math + && let Some(location) = left_delimiters.last() + { + return Err(math_delimiter_error( + location, + "missing `\\right` for this `\\left`", + )); + } + if let Some(location) = mode.math_opened_at() { + return Err(math_delimiter_error( + location, + "math mode has no matching closing delimiter", + )); + } + Ok(()) +} + +pub fn math_delimiter_error(location: &SourceLocation, message: &str) -> String { + let origin = match &location.origin { + SourceOrigin::File(path) => path.display().to_string(), + SourceOrigin::Terminal => "".to_string(), + }; + format!("{origin}:{}:{}: {message}", location.line, location.column) +} diff --git a/crates/texrra-core/src/math_parser.rs b/crates/texrra-core/src/math_parser.rs new file mode 100644 index 0000000..7cc28bf --- /dev/null +++ b/crates/texrra-core/src/math_parser.rs @@ -0,0 +1,2072 @@ +use std::{ops::Range, sync::Arc}; + +use crate::{ + MathClass, MathStyleCommand, expanded as tex_expansion, + math_expr::{ + MathAccent, MathDelimiterGlyph, MathDelimiterSettings, MathExpr, MathFontFamilies, + MathFontStyle, MathFractionStyle, MathInfixFractionKind, MathLimitMode, + MathLineBreakPenalties, MathPhantomKind, + }, + source::{SourceLocation, SourceOrigin}, +}; + +pub fn parse_math_expression_with_events( + expanded: &tex_expansion::ExpandedTokenStream, + range: Range, + events: &[tex_expansion::FrontendEvent], +) -> Result { + let range_len = range.end - range.start; + + if let Some((event_index, event)) = find_math_infix_fraction_event(&range, events) { + let numerator = parse_math_expression_with_events( + expanded, + range.start..event.position, + &events[..event_index], + )?; + let denominator = parse_math_expression_with_events( + expanded, + event.position..range.end, + &events[event_index + 1..], + )?; + let (has_rule, parentheses, rule_thickness, delimiters, delimiter_settings, math_fonts) = + match &event.kind { + tex_expansion::FrontendEventKind::MathInfixFraction(kind, math_fonts) => match kind + { + MathInfixFractionKind::Over => (true, false, None, None, None, math_fonts), + MathInfixFractionKind::Atop => (false, false, None, None, None, math_fonts), + MathInfixFractionKind::Choose(settings) => { + (false, true, None, None, Some(*settings), math_fonts) + } + MathInfixFractionKind::Above(thickness) => { + (true, false, Some(*thickness), None, None, math_fonts) + } + MathInfixFractionKind::OverWithDelims(delimiters) => ( + true, + false, + None, + Some(delimiters), + Some(delimiters.settings), + math_fonts, + ), + MathInfixFractionKind::AtopWithDelims(delimiters) => ( + false, + false, + None, + Some(delimiters), + Some(delimiters.settings), + math_fonts, + ), + MathInfixFractionKind::AboveWithDelims { + thickness, + delimiters, + } => ( + true, + false, + Some(*thickness), + Some(delimiters), + Some(delimiters.settings), + math_fonts, + ), + }, + _ => unreachable!("only infix fraction events are selected"), + }; + let math_fonts = Arc::clone(math_fonts); + let fraction = MathExpr::Fraction { + numerator: Box::new(numerator), + denominator: Box::new(denominator), + style: MathFractionStyle::Automatic, + has_rule, + rule_thickness, + math_fonts: Arc::clone(&math_fonts), + }; + let expression = if parentheses { + MathExpr::Delimited { + left: MathDelimiterGlyph::plain_with_math_fonts("(", Arc::clone(&math_fonts)), + body: Box::new(fraction), + right: MathDelimiterGlyph::plain_with_math_fonts(")", math_fonts), + left_settings: delimiter_settings.unwrap_or_default(), + right_settings: delimiter_settings.unwrap_or_default(), + } + } else if let Some(delimiters) = delimiters { + MathExpr::Delimited { + left: delimiters.left.clone(), + body: Box::new(fraction), + right: delimiters.right.clone(), + left_settings: delimiters.settings, + right_settings: delimiters.settings, + } + } else { + fraction + }; + return Ok(with_source( + expanded, + range, + with_location(Some(event.location.clone()), expression), + )); + } + + let mut items = Vec::new(); + let mut active_math_line_break_penalties = MathLineBreakPenalties::default(); + let mut cursor = 0usize; + let mut fraction_search_after = 0usize; + let mut root_search_after = 0usize; + let mut delimiter_search_after = 0usize; + let mut group_search_after = 0usize; + let mut math_space_search_after = 0usize; + let mut math_character_search_after = 0usize; + let mut math_style_search_after = 0usize; + let mut math_choice_search_after = 0usize; + let mut literal_character_search_after = 0usize; + let mut event_index = events.partition_point(|event| event.position < range.start); + let mut pending_limit_mode = None; + let mut active_spacing = None; + while cursor < range_len + || events.iter().skip(math_space_search_after).any(|event| { + event.position == range.start + cursor + && matches!( + &event.kind, + tex_expansion::FrontendEventKind::MathSpace(_) + | tex_expansion::FrontendEventKind::HorizontalGlue(_) + | tex_expansion::FrontendEventKind::Kern(_) + | tex_expansion::FrontendEventKind::Penalty(_) + ) + }) + || events.iter().skip(math_style_search_after).any(|event| { + event.position == range.start + cursor + && matches!( + &event.kind, + tex_expansion::FrontendEventKind::MathStyleChange(_) + ) + }) + || events.iter().skip(math_choice_search_after).any(|event| { + event.position == range.start + cursor + && matches!( + &event.kind, + tex_expansion::FrontendEventKind::MathChoiceStart + ) + }) + || events + .iter() + .skip(math_character_search_after) + .any(|event| { + event.position == range.start + cursor + && matches!( + &event.kind, + tex_expansion::FrontendEventKind::MathCharacter { .. } + | tex_expansion::FrontendEventKind::MathUnicodeCharacter { .. } + | tex_expansion::FrontendEventKind::MathUnicodeDelimiter { .. } + ) + }) + || events + .iter() + .skip(literal_character_search_after) + .any(|event| { + event.position == range.start + cursor + && matches!( + &event.kind, + tex_expansion::FrontendEventKind::LiteralAmpersand + | tex_expansion::FrontendEventKind::LiteralCharacter(_) + | tex_expansion::FrontendEventKind::LineBreak + | tex_expansion::FrontendEventKind::MathManualDelimiter { .. } + ) + }) + { + let absolute_cursor = range.start + cursor; + if let Some(item) = expanded.next_token_item_at_or_after(absolute_cursor, range.end) { + if active_spacing != Some(item.math_spacing) { + items.push(MathExpr::MathSpacingChange(item.math_spacing)); + active_spacing = Some(item.math_spacing); + } + } + while events + .get(event_index) + .is_some_and(|event| event.position < absolute_cursor) + { + event_index += 1; + } + while let Some(event) = events + .get(event_index) + .filter(|event| event.position == absolute_cursor) + { + match &event.kind { + tex_expansion::FrontendEventKind::MathLimitMode(mode) => { + pending_limit_mode = Some(*mode); + } + tex_expansion::FrontendEventKind::MathSpace(_) + | tex_expansion::FrontendEventKind::HorizontalGlue(_) + | tex_expansion::FrontendEventKind::Kern(_) + | tex_expansion::FrontendEventKind::Penalty(_) => pending_limit_mode = None, + _ => {} + } + event_index += 1; + } + if pending_limit_mode.is_some() + && expanded + .token_value_at(absolute_cursor) + .and_then(tex_expansion::ExpandedTokenValue::character) + .is_some_and(|character| { + !character.is_whitespace() && !matches!(character, '^' | '_') + }) + { + pending_limit_mode = None; + } + let fraction_span = + find_math_fraction_span(events, absolute_cursor, range.end, fraction_search_after); + let root_span = find_math_root_span(events, absolute_cursor, range.end, root_search_after); + let delimiter_span = + find_math_delimiter_span(events, absolute_cursor, range.end, delimiter_search_after); + let group_span = + find_math_group_span(events, absolute_cursor, range.end, group_search_after); + let choice_span = + find_math_choice_span(events, absolute_cursor, range.end, math_choice_search_after); + let math_space_event = events + .iter() + .enumerate() + .skip(math_space_search_after) + .find(|(_, event)| { + event.position == absolute_cursor + && matches!( + &event.kind, + tex_expansion::FrontendEventKind::MathSpace(_) + | tex_expansion::FrontendEventKind::HorizontalGlue(_) + | tex_expansion::FrontendEventKind::Kern(_) + | tex_expansion::FrontendEventKind::Penalty(_) + ) + }); + let literal_character_event = events + .iter() + .enumerate() + .skip(literal_character_search_after) + .find(|(_, event)| { + event.position == absolute_cursor + && matches!( + &event.kind, + tex_expansion::FrontendEventKind::LiteralAmpersand + | tex_expansion::FrontendEventKind::LiteralCharacter(_) + | tex_expansion::FrontendEventKind::LineBreak + | tex_expansion::FrontendEventKind::MathManualDelimiter { .. } + ) + }); + let math_style_event = events + .iter() + .enumerate() + .skip(math_style_search_after) + .find(|(_, event)| { + event.position == absolute_cursor + && matches!( + &event.kind, + tex_expansion::FrontendEventKind::MathStyleChange(_) + ) + }); + let math_character_event = events + .iter() + .enumerate() + .skip(math_character_search_after) + .find(|(_, event)| { + event.position == absolute_cursor + && matches!( + &event.kind, + tex_expansion::FrontendEventKind::MathCharacter { .. } + | tex_expansion::FrontendEventKind::MathUnicodeCharacter { .. } + ) + }); + let first_container_event = fraction_span + .as_ref() + .map(|span| span.start_event) + .into_iter() + .chain(root_span.as_ref().map(|span| span.start_event)) + .chain(delimiter_span.as_ref().map(|span| span.start_event)) + .chain(group_span.as_ref().map(|span| span.start_event)) + .chain(choice_span.as_ref().map(|span| span.start_event)) + .min(); + let next_inline_event = [ + math_space_event, + literal_character_event, + math_style_event, + math_character_event, + ] + .into_iter() + .flatten() + .min_by_key(|(event_index, _)| *event_index); + let next_inline_event = next_inline_event.filter(|(inline_event_index, _)| { + first_container_event.is_none_or(|container| *inline_event_index < container) + }); + if let Some((inline_event_index, event)) = next_inline_event { + let expression = match &event.kind { + tex_expansion::FrontendEventKind::MathSpace(units) => { + math_space_search_after = inline_event_index + 1; + MathExpr::Space(*units) + } + tex_expansion::FrontendEventKind::Kern(width) => { + math_space_search_after = inline_event_index + 1; + MathExpr::Kern(*width) + } + tex_expansion::FrontendEventKind::HorizontalGlue(glue) => { + math_space_search_after = inline_event_index + 1; + MathExpr::Glue(*glue) + } + tex_expansion::FrontendEventKind::Penalty(penalty) => { + math_space_search_after = inline_event_index + 1; + MathExpr::BreakPenalty(*penalty) + } + tex_expansion::FrontendEventKind::MathStyleChange(style) => { + math_style_search_after = inline_event_index + 1; + MathExpr::MathStyleChange(*style) + } + tex_expansion::FrontendEventKind::MathCharacter { + code, + active_family, + math_fonts, + } => { + math_character_search_after = inline_event_index + 1; + let character = char::from_u32(u32::from(code & 0xff)) + .expect("an eight-bit math slot is a valid character"); + let (class, math_family, math_slot) = + math_code_properties(character, Some(*code), Some(*active_family)); + MathExpr::Atom { + class, + text: character.to_string(), + math_family, + math_slots: math_slot.into_iter().collect(), + math_fonts: Arc::clone(math_fonts), + } + } + tex_expansion::FrontendEventKind::MathUnicodeCharacter { + class, + family, + character, + math_fonts, + } => { + math_character_search_after = inline_event_index + 1; + MathExpr::Atom { + class: *class, + text: character.to_string(), + math_family: Some(*family), + math_slots: Vec::new(), + math_fonts: Arc::clone(math_fonts), + } + } + tex_expansion::FrontendEventKind::MathUnicodeDelimiter { + class, + family, + character, + settings, + math_fonts, + } => { + math_character_search_after = inline_event_index + 1; + MathExpr::UnicodeDelimiter { + character: *character, + class: *class, + family: *family, + settings: *settings, + math_fonts: Arc::clone(math_fonts), + } + } + tex_expansion::FrontendEventKind::LiteralAmpersand => { + literal_character_search_after = inline_event_index + 1; + MathExpr::Atom { + class: MathClass::Ordinary, + text: "&".to_string(), + math_family: None, + math_slots: Vec::new(), + math_fonts: Arc::default(), + } + } + tex_expansion::FrontendEventKind::LiteralCharacter(character) => { + literal_character_search_after = inline_event_index + 1; + MathExpr::Atom { + class: match character { + '{' => MathClass::Opening, + '}' => MathClass::Closing, + _ => math_class_for_character(*character), + }, + text: character.to_string(), + math_family: None, + math_slots: Vec::new(), + math_fonts: Arc::default(), + } + } + tex_expansion::FrontendEventKind::LineBreak => { + literal_character_search_after = inline_event_index + 1; + MathExpr::Space(1) + } + tex_expansion::FrontendEventKind::MathManualDelimiter { + delimiter, + half_points, + class, + settings, + math_fonts, + } => { + literal_character_search_after = inline_event_index + 1; + MathExpr::SizedDelimiter { + delimiter: delimiter.clone(), + half_points: *half_points, + class: *class, + settings: *settings, + math_fonts: Arc::clone(math_fonts), + } + } + _ => unreachable!("only inline math events are selected here"), + }; + if active_math_line_break_penalties != event.math_line_break_penalties { + items.push(MathExpr::MathLineBreakPenaltiesChange( + event.math_line_break_penalties, + )); + active_math_line_break_penalties = event.math_line_break_penalties; + } + items.push(with_location(Some(event.location.clone()), expression)); + continue; + } + if group_span.as_ref().is_some_and(|group| { + fraction_span + .as_ref() + .is_none_or(|fraction| group.start_event < fraction.start_event) + && root_span + .as_ref() + .is_none_or(|root| group.start_event < root.start_event) + && delimiter_span + .as_ref() + .is_none_or(|delimiter| group.start_event < delimiter.start_event) + && choice_span + .as_ref() + .is_none_or(|choice| group.start_event < choice.start_event) + }) { + let span = group_span.expect("math group span was selected"); + let body_range = absolute_cursor..span.end_position; + let is_scope = matches!(&span.value, MathGroupValue::Scope); + let body = match span.value { + MathGroupValue::Scope => parse_math_expression_with_events( + expanded, + body_range.clone(), + &events[span.start_event + 1..span.end_event], + )?, + MathGroupValue::Accent { + position, + family, + math_fonts, + } => MathExpr::Accent { + position, + body: Box::new(parse_math_expression_with_events( + expanded, + body_range.clone(), + &events[span.start_event + 1..span.end_event], + )?), + family, + math_fonts, + }, + MathGroupValue::Font(MathFontStyle::Text) => { + parse_math_text_group(expanded, body_range.clone()) + } + MathGroupValue::Font(font) => { + let mut expression = parse_math_expression_with_events( + expanded, + body_range.clone(), + &events[span.start_event + 1..span.end_event], + )?; + match font { + MathFontStyle::Roman + | MathFontStyle::BoldRoman + | MathFontStyle::SansSerif + | MathFontStyle::Calligraphic + | MathFontStyle::Blackboard + | MathFontStyle::Fraktur => { + force_math_family(&mut expression, 1, 0); + } + MathFontStyle::Monospace => { + force_monospace_math_font(&mut expression); + } + _ => {} + } + if font == MathFontStyle::Monospace { + expression + } else { + MathExpr::Styled { + font, + expression: Box::new(expression), + } + } + } + MathGroupValue::Operator => MathExpr::Atom { + class: MathClass::Operator, + text: expanded.character_tokens_in(body_range), + math_family: None, + math_slots: Vec::new(), + math_fonts: Arc::default(), + }, + MathGroupValue::Classified(class) => MathExpr::Classified { + class, + body: Box::new(parse_math_expression_with_events( + expanded, + body_range.clone(), + &events[span.start_event + 1..span.end_event], + )?), + }, + MathGroupValue::Phantom(kind) => MathExpr::Phantom { + kind, + body: Box::new(parse_math_expression_with_events( + expanded, + body_range.clone(), + &events[span.start_event + 1..span.end_event], + )?), + }, + }; + if is_scope { + append_math_scope(&mut items, body, Some(span.location)); + } else { + items.push(with_location(Some(span.location), body)); + } + cursor = span.end_position - range.start; + fraction_search_after = span.end_event + 1; + root_search_after = span.end_event + 1; + delimiter_search_after = span.end_event + 1; + group_search_after = span.end_event + 1; + math_space_search_after = span.end_event + 1; + math_character_search_after = span.end_event + 1; + math_style_search_after = span.end_event + 1; + math_choice_search_after = span.end_event + 1; + continue; + } + if choice_span.as_ref().is_some_and(|choice| { + fraction_span + .as_ref() + .is_none_or(|fraction| choice.start_event < fraction.start_event) + && root_span + .as_ref() + .is_none_or(|root| choice.start_event < root.start_event) + && delimiter_span + .as_ref() + .is_none_or(|delimiter| choice.start_event < delimiter.start_event) + && group_span + .as_ref() + .is_none_or(|group| choice.start_event < group.start_event) + }) { + let span = choice_span.expect("math choice span was selected"); + let mut display = None; + let mut text = None; + let mut script = None; + let mut scriptscript = None; + for branch in &span.branches { + let expression = Box::new(parse_math_expression_with_events( + expanded, + branch.start_position..branch.end_position, + &events[branch.start_event + 1..branch.end_event], + )?); + match branch.style { + MathStyleCommand::Display => display = Some(expression), + MathStyleCommand::Text => text = Some(expression), + MathStyleCommand::Script => script = Some(expression), + MathStyleCommand::ScriptScript => scriptscript = Some(expression), + } + } + let expression = MathExpr::MathChoice { + display: display.expect("mathchoice has a display branch"), + text: text.expect("mathchoice has a text branch"), + script: script.expect("mathchoice has a script branch"), + scriptscript: scriptscript.expect("mathchoice has a scriptscript branch"), + }; + items.push(with_location( + Some(span.location), + with_source(expanded, absolute_cursor..span.end_position, expression), + )); + cursor = span.end_position - range.start; + fraction_search_after = span.end_event + 1; + root_search_after = span.end_event + 1; + delimiter_search_after = span.end_event + 1; + group_search_after = span.end_event + 1; + math_space_search_after = span.end_event + 1; + math_character_search_after = span.end_event + 1; + math_style_search_after = span.end_event + 1; + math_choice_search_after = span.end_event + 1; + event_index = span.end_event + 1; + continue; + } + if delimiter_span.as_ref().is_some_and(|delimiter| { + fraction_span + .as_ref() + .is_none_or(|fraction| delimiter.start_event < fraction.start_event) + && root_span + .as_ref() + .is_none_or(|root| delimiter.start_event < root.start_event) + }) { + let span = delimiter_span.expect("delimiter span was selected"); + let expression = if span.middles.is_empty() { + let body = parse_math_expression_with_events( + expanded, + absolute_cursor..span.end_position, + &events[span.start_event + 1..span.end_event], + )?; + MathExpr::Delimited { + left: span.left.clone(), + body: Box::new(body), + right: span.right.clone(), + left_settings: span.left_settings, + right_settings: span.right_settings, + } + } else { + let mut delimiters = vec![span.left.clone()]; + let mut delimiter_settings = vec![span.left_settings]; + let mut segments = Vec::with_capacity(span.middles.len() + 1); + let mut segment_start = absolute_cursor; + let mut segment_event_start = span.start_event + 1; + for (delimiter, settings, position, event_index) in &span.middles { + segments.push(parse_math_expression_with_events( + expanded, + segment_start..*position, + &events[segment_event_start..*event_index], + )?); + delimiters.push(delimiter.clone()); + delimiter_settings.push(*settings); + segment_start = *position; + segment_event_start = *event_index + 1; + } + segments.push(parse_math_expression_with_events( + expanded, + segment_start..span.end_position, + &events[segment_event_start..span.end_event], + )?); + delimiters.push(span.right.clone()); + delimiter_settings.push(span.right_settings); + MathExpr::Fenced { + delimiters, + delimiter_settings, + segments, + } + }; + items.push(with_location( + Some(span.location), + with_source(expanded, absolute_cursor..span.end_position, expression), + )); + cursor = span.end_position - range.start; + fraction_search_after = span.end_event + 1; + root_search_after = span.end_event + 1; + delimiter_search_after = span.end_event + 1; + group_search_after = span.end_event + 1; + math_space_search_after = span.end_event + 1; + math_character_search_after = span.end_event + 1; + math_style_search_after = span.end_event + 1; + math_choice_search_after = span.end_event + 1; + continue; + } + if root_span.as_ref().is_some_and(|root| { + fraction_span + .as_ref() + .is_none_or(|fraction| root.start_event < fraction.start_event) + && delimiter_span + .as_ref() + .is_none_or(|delimiter| root.start_event < delimiter.start_event) + }) { + let span = root_span.expect("root span was selected"); + let index = if span.has_index { + Some(parse_math_expression_with_events( + expanded, + absolute_cursor..span.separator_position, + &events[span.start_event + 1..span.separator_event], + )?) + } else { + None + }; + let body = parse_math_expression_with_events( + expanded, + span.separator_position..span.end_position, + &events[span.separator_event + 1..span.end_event], + )?; + items.push(with_location( + Some(span.location), + with_source( + expanded, + absolute_cursor..span.end_position, + MathExpr::Root { + index: index.map(Box::new), + body: Box::new(body), + radical: span.radical, + math_fonts: span.math_fonts, + }, + ), + )); + cursor = span.end_position - range.start; + fraction_search_after = span.end_event + 1; + root_search_after = span.end_event + 1; + delimiter_search_after = span.end_event + 1; + group_search_after = span.end_event + 1; + math_space_search_after = span.end_event + 1; + math_character_search_after = span.end_event + 1; + math_style_search_after = span.end_event + 1; + math_choice_search_after = span.end_event + 1; + continue; + } + if let Some(span) = fraction_span { + let numerator_range = absolute_cursor..span.separator_position; + let denominator_range = span.separator_position..span.end_position; + let numerator = parse_math_expression_with_events( + expanded, + numerator_range, + &events[span.start_event + 1..span.separator_event], + )?; + let denominator = parse_math_expression_with_events( + expanded, + denominator_range, + &events[span.separator_event + 1..span.end_event], + )?; + let fraction = MathExpr::Fraction { + numerator: Box::new(numerator), + denominator: Box::new(denominator), + style: span.style, + has_rule: span.has_rule, + rule_thickness: span.rule_thickness, + math_fonts: Arc::clone(&span.math_fonts), + }; + let expression = if span.parentheses { + MathExpr::Delimited { + left: MathDelimiterGlyph::plain_with_math_fonts( + "(", + Arc::clone(&span.math_fonts), + ), + body: Box::new(fraction), + right: MathDelimiterGlyph::plain_with_math_fonts(")", span.math_fonts), + left_settings: span.delimiter_settings, + right_settings: span.delimiter_settings, + } + } else { + fraction + }; + items.push(with_location(Some(span.location), expression)); + cursor = span.end_position - range.start; + fraction_search_after = span.end_event + 1; + root_search_after = span.end_event + 1; + delimiter_search_after = span.end_event + 1; + group_search_after = span.end_event + 1; + math_space_search_after = span.end_event + 1; + math_character_search_after = span.end_event + 1; + math_style_search_after = span.end_event + 1; + math_choice_search_after = span.end_event + 1; + continue; + } + let expanded_token = expanded.token_item_at(absolute_cursor); + let math_code = expanded_token.and_then(|item| item.math_code); + let active_math_family = expanded_token.and_then(|item| item.math_family); + let unicode_math_code = expanded_token.and_then(|item| item.unicode_math_code); + let math_fonts = expanded_token + .map(|item| Arc::clone(&item.math_fonts)) + .unwrap_or_default(); + let token_character = expanded_token.and_then(|item| match &item.kind { + tex_expansion::ExpandedItemKind::Token(value) => value.character(), + tex_expansion::ExpandedItemKind::Event(_) => None, + }); + let cursor_advance = expanded_token + .map(|item| item.end_position - absolute_cursor) + .or_else(|| { + expanded + .next_token_item_at_or_after(absolute_cursor + 1, range.end) + .map(|item| item.position - absolute_cursor) + }) + .unwrap_or(range.end - absolute_cursor); + let script_direction = match expanded.token_value_at(absolute_cursor) { + Some(tex_expansion::ExpandedTokenValue::Superscript(_)) => Some(true), + Some(tex_expansion::ExpandedTokenValue::Subscript(_)) => Some(false), + _ => None, + }; + if let Some(superscript) = script_direction.filter(|_| token_character.is_some()) { + if let Some((script_range, after)) = read_math_argument_with_events( + expanded, + &range, + events, + cursor + cursor_advance, + event_index, + ) { + let script = parse_child_expression(expanded, events, script_range)?; + attach_math_script( + &mut items, + superscript, + script, + expanded.source_at(absolute_cursor), + pending_limit_mode.take(), + )?; + cursor = after; + continue; + } + let location = expanded.source_at(absolute_cursor); + return Err(math_parse_error(location.as_ref(), "Missing { inserted")); + } + if let Some(character) = token_character { + if !character.is_whitespace() { + if let Some(item) = expanded_token { + if active_math_line_break_penalties != item.math_line_break_penalties { + items.push(MathExpr::MathLineBreakPenaltiesChange( + item.math_line_break_penalties, + )); + active_math_line_break_penalties = item.math_line_break_penalties; + } + } + let (class, character, math_family, math_slot) = + if let Some(unicode_math_code) = unicode_math_code { + ( + unicode_math_code.math_class(), + unicode_math_code.character(), + Some(unicode_math_code.math_family(active_math_family)), + None, + ) + } else { + let (class, math_family, math_slot) = + math_code_properties(character, math_code, active_math_family); + (class, character, math_family, math_slot) + }; + append_math_text( + &mut items, + character, + class, + math_family, + math_slot, + math_fonts, + expanded.source_at(absolute_cursor), + ); + } + } + if cursor_advance == 0 { + break; + } + cursor += cursor_advance; + } + let expression = match items.len() { + 0 => MathExpr::Text(String::new()), + 1 => items.pop().unwrap(), + _ => MathExpr::Sequence(items), + }; + Ok(with_source(expanded, range, expression)) +} + +fn parse_math_text_group( + expanded: &tex_expansion::ExpandedTokenStream, + range: Range, +) -> MathExpr { + use tex_expansion::{ExpandedItemKind as Item, FrontendEventKind as Event, TextStyle}; + + let mut runs = Vec::new(); + let mut text = String::new(); + let mut bold = false; + let mut italic = false; + let mut monospace = false; + let mut style_stack = Vec::new(); + let item_start = expanded + .items + .partition_point(|item| item.position < range.start); + + for item in expanded.items[item_start..] + .iter() + .take_while(|item| item.position < range.end) + { + match &item.kind { + Item::Token(token) => { + if let Some(character) = token.character() { + text.push(character); + } + } + Item::Event(Event::TextStyleStart(style)) => { + push_math_text_run(&mut runs, &mut text, bold, italic, monospace); + style_stack.push((*style, bold, italic, monospace)); + match style { + TextStyle::Bold => bold = true, + TextStyle::Italic => italic = true, + TextStyle::Monospace => monospace = true, + TextStyle::SmallCaps => {} + TextStyle::Normal => { + bold = false; + italic = false; + monospace = false; + } + } + } + Item::Event(Event::TextStyleEnd(style)) => { + push_math_text_run(&mut runs, &mut text, bold, italic, monospace); + if style_stack + .last() + .is_some_and(|(active, _, _, _)| active == style) + { + if let Some((_, previous_bold, previous_italic, previous_monospace)) = + style_stack.pop() + { + bold = previous_bold; + italic = previous_italic; + monospace = previous_monospace; + } + } + } + Item::Event(Event::LiteralAmpersand) => text.push('&'), + Item::Event(Event::LiteralCharacter(character)) => text.push(*character), + Item::Event(Event::LineBreak | Event::RowBreak) => text.push(' '), + _ => {} + } + } + push_math_text_run(&mut runs, &mut text, bold, italic, monospace); + + match runs.len() { + 0 => MathExpr::Text(String::new()), + 1 => runs.pop().expect("one text run was collected"), + _ => MathExpr::Sequence(runs), + } +} + +fn push_math_text_run( + runs: &mut Vec, + text: &mut String, + bold: bool, + italic: bool, + monospace: bool, +) { + if text.is_empty() { + return; + } + let text = std::mem::take(text); + if bold || italic || monospace { + runs.push(MathExpr::TextStyled { + text, + bold, + italic, + monospace, + }); + } else { + runs.push(MathExpr::Text(text)); + } +} + +fn force_monospace_math_font(expression: &mut MathExpr) { + match expression { + MathExpr::Spanned { expression, .. } => force_monospace_math_font(expression), + MathExpr::Classified { body, .. } + | MathExpr::Phantom { body, .. } + | MathExpr::Accent { body, .. } => { + force_monospace_math_font(body); + } + MathExpr::Sequence(items) => { + for item in items { + force_monospace_math_font(item); + } + } + MathExpr::Alignment { rows, .. } => { + for item in rows.iter_mut().flatten() { + force_monospace_math_font(item); + } + } + MathExpr::Fraction { + numerator, + denominator, + .. + } => { + force_monospace_math_font(numerator); + force_monospace_math_font(denominator); + } + MathExpr::MathChoice { + display, + text, + script, + scriptscript, + } => { + force_monospace_math_font(display); + force_monospace_math_font(text); + force_monospace_math_font(script); + force_monospace_math_font(scriptscript); + } + MathExpr::Root { index, body, .. } => { + if let Some(index) = index { + force_monospace_math_font(index); + } + force_monospace_math_font(body); + } + MathExpr::Delimited { body, .. } => force_monospace_math_font(body), + MathExpr::Fenced { segments, .. } => { + for segment in segments { + force_monospace_math_font(segment); + } + } + MathExpr::Script { + base, + sub, + superscript, + .. + } => { + force_monospace_math_font(base); + if let Some(sub) = sub { + force_monospace_math_font(sub); + } + if let Some(superscript) = superscript { + force_monospace_math_font(superscript); + } + } + MathExpr::Atom { + class: MathClass::Ordinary, + text, + .. + } => { + *expression = MathExpr::TextStyled { + text: std::mem::take(text), + bold: false, + italic: false, + monospace: true, + }; + } + MathExpr::TextStyled { monospace, .. } => *monospace = true, + MathExpr::Text(_) + | MathExpr::Styled { .. } + | MathExpr::Atom { .. } + | MathExpr::MathSpacingChange(_) + | MathExpr::MathLineBreakPenaltiesChange(_) + | MathExpr::BreakPenalty(_) + | MathExpr::MathStyleChange(_) + | MathExpr::Space(_) + | MathExpr::Glue(_) + | MathExpr::Kern(_) + | MathExpr::SizedDelimiter { .. } + | MathExpr::UnicodeDelimiter { .. } => {} + } +} + +fn find_math_infix_fraction_event<'a>( + range: &Range, + events: &'a [tex_expansion::FrontendEvent], +) -> Option<(usize, &'a tex_expansion::FrontendEvent)> { + use tex_expansion::FrontendEventKind as Event; + + let mut group_depth = 0usize; + let mut fraction_depth = 0usize; + let mut root_depth = 0usize; + let mut delimiter_depth = 0usize; + let mut choice_depth = 0usize; + let mut wrapped_group_depth = 0usize; + for (index, event) in events.iter().enumerate() { + if event.position < range.start { + continue; + } + if event.position >= range.end { + break; + } + match &event.kind { + Event::MathInfixFraction(..) + if group_depth + + fraction_depth + + root_depth + + delimiter_depth + + choice_depth + + wrapped_group_depth + == 0 => + { + return Some((index, event)); + } + Event::GroupStart => group_depth += 1, + Event::GroupEnd => group_depth = group_depth.saturating_sub(1), + Event::MathFractionStart { .. } => fraction_depth += 1, + Event::MathFractionEnd => fraction_depth = fraction_depth.saturating_sub(1), + Event::MathRootStart { .. } => root_depth += 1, + Event::MathRootEnd => root_depth = root_depth.saturating_sub(1), + Event::MathDelimiterStart { .. } => delimiter_depth += 1, + Event::MathDelimiterEnd { .. } => delimiter_depth = delimiter_depth.saturating_sub(1), + Event::MathChoiceStart => choice_depth += 1, + Event::MathChoiceEnd => choice_depth = choice_depth.saturating_sub(1), + Event::MathAccentStart { .. } + | Event::MathFontStart(_) + | Event::MathOperatorStart + | Event::MathClassStart(_) => wrapped_group_depth += 1, + Event::MathAccentEnd + | Event::MathFontEnd + | Event::MathOperatorEnd + | Event::MathClassEnd => wrapped_group_depth = wrapped_group_depth.saturating_sub(1), + _ => {} + } + } + None +} + +struct MathFractionSpan { + style: MathFractionStyle, + has_rule: bool, + rule_thickness: Option, + parentheses: bool, + delimiter_settings: MathDelimiterSettings, + math_fonts: MathFontFamilies, + start_event: usize, + separator_event: usize, + end_event: usize, + separator_position: usize, + end_position: usize, + location: SourceLocation, +} + +struct MathRootSpan { + has_index: bool, + radical: Option<(u8, char)>, + math_fonts: MathFontFamilies, + start_event: usize, + separator_event: usize, + end_event: usize, + separator_position: usize, + end_position: usize, + location: SourceLocation, +} + +struct MathDelimiterSpan { + left: MathDelimiterGlyph, + left_settings: MathDelimiterSettings, + right: MathDelimiterGlyph, + right_settings: MathDelimiterSettings, + middles: Vec<(MathDelimiterGlyph, MathDelimiterSettings, usize, usize)>, + start_event: usize, + end_event: usize, + end_position: usize, + location: SourceLocation, +} + +struct MathChoiceSpan { + branches: Vec, + start_event: usize, + end_event: usize, + end_position: usize, + location: SourceLocation, +} + +struct MathChoiceBranchSpan { + style: MathStyleCommand, + start_event: usize, + end_event: usize, + start_position: usize, + end_position: usize, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MathGroupType { + Accent, + Classified, + Font, + Operator, + Phantom, + Scope, +} + +#[derive(Clone)] +enum MathGroupValue { + Accent { + position: MathAccent, + family: u8, + math_fonts: MathFontFamilies, + }, + Classified(MathClass), + Font(MathFontStyle), + Operator, + Phantom(MathPhantomKind), + Scope, +} + +struct MathGroupSpan { + value: MathGroupValue, + start_event: usize, + end_event: usize, + end_position: usize, + location: SourceLocation, +} + +fn math_group_marker( + kind: &tex_expansion::FrontendEventKind, +) -> Option<(MathGroupType, bool, Option)> { + use tex_expansion::FrontendEventKind as Event; + + match kind { + Event::MathAccentStart { + accent, + family, + math_fonts, + } => Some(( + MathGroupType::Accent, + true, + Some(MathGroupValue::Accent { + position: *accent, + family: *family, + math_fonts: Arc::clone(math_fonts), + }), + )), + Event::MathAccentEnd => Some((MathGroupType::Accent, false, None)), + Event::MathFontStart(font) => { + Some((MathGroupType::Font, true, Some(MathGroupValue::Font(*font)))) + } + Event::MathFontEnd => Some((MathGroupType::Font, false, None)), + Event::MathPhantomStart(kind) => Some(( + MathGroupType::Phantom, + true, + Some(MathGroupValue::Phantom(*kind)), + )), + Event::MathPhantomEnd => Some((MathGroupType::Phantom, false, None)), + Event::MathOperatorStart => Some(( + MathGroupType::Operator, + true, + Some(MathGroupValue::Operator), + )), + Event::MathOperatorEnd => Some((MathGroupType::Operator, false, None)), + Event::MathClassStart(class) => Some(( + MathGroupType::Classified, + true, + Some(MathGroupValue::Classified(*class)), + )), + Event::MathClassEnd => Some((MathGroupType::Classified, false, None)), + Event::GroupStart => Some((MathGroupType::Scope, true, Some(MathGroupValue::Scope))), + Event::GroupEnd => Some((MathGroupType::Scope, false, None)), + _ => None, + } +} + +fn find_math_group_span( + events: &[tex_expansion::FrontendEvent], + start_position: usize, + limit: usize, + search_after: usize, +) -> Option { + let (start_event, group_type, value, location) = events + .iter() + .enumerate() + .skip(search_after) + .find_map(|(index, event)| { + if event.position != start_position { + return None; + } + let (group_type, is_start, value) = math_group_marker(&event.kind)?; + if is_start { + Some((index, group_type, value?, event.location.clone())) + } else { + None + } + })?; + let mut stack = vec![group_type]; + for (index, event) in events.iter().enumerate().skip(start_event + 1) { + if event.position > limit { + break; + } + let Some((marker_type, is_start, _)) = math_group_marker(&event.kind) else { + continue; + }; + if is_start { + stack.push(marker_type); + } else if stack.last() == Some(&marker_type) { + stack.pop(); + if stack.is_empty() { + return Some(MathGroupSpan { + value, + start_event, + end_event: index, + end_position: event.position, + location, + }); + } + } else { + return None; + } + } + None +} + +fn find_math_fraction_span( + events: &[tex_expansion::FrontendEvent], + start_position: usize, + limit: usize, + search_after: usize, +) -> Option { + use tex_expansion::FrontendEventKind as Event; + + let (start_event, start) = + events + .iter() + .enumerate() + .skip(search_after) + .find_map(|(index, event)| { + if event.position != start_position { + return None; + } + match &event.kind { + Event::MathFractionStart { + style, + has_rule, + parentheses, + delimiter_settings, + math_fonts, + } => Some(( + index, + ( + *style, + *has_rule, + *parentheses, + *delimiter_settings, + Arc::clone(math_fonts), + event.location.clone(), + ), + )), + _ => None, + } + })?; + let (style, has_rule, parentheses, delimiter_settings, math_fonts, location) = start; + let mut depth = 1usize; + let mut separator_event = None; + for (index, event) in events.iter().enumerate().skip(start_event + 1) { + if event.position > limit { + break; + } + match &event.kind { + Event::MathFractionStart { .. } => depth += 1, + Event::MathFractionSeparator if depth == 1 && separator_event.is_none() => { + separator_event = Some(index); + } + Event::MathFractionEnd if depth == 1 => { + let separator_event = separator_event?; + return Some(MathFractionSpan { + style, + has_rule, + rule_thickness: None, + parentheses, + delimiter_settings, + math_fonts, + start_event, + separator_event, + end_event: index, + separator_position: events[separator_event].position, + end_position: event.position, + location, + }); + } + Event::MathFractionEnd => depth -= 1, + _ => {} + } + } + None +} + +fn find_math_root_span( + events: &[tex_expansion::FrontendEvent], + start_position: usize, + limit: usize, + search_after: usize, +) -> Option { + use tex_expansion::FrontendEventKind as Event; + + let (start_event, has_index, radical, math_fonts, location) = events + .iter() + .enumerate() + .skip(search_after) + .find_map(|(index, event)| { + if event.position != start_position { + return None; + } + match &event.kind { + Event::MathRootStart { + has_index, + radical, + math_fonts, + } => Some(( + index, + *has_index, + *radical, + Arc::clone(math_fonts), + event.location.clone(), + )), + _ => None, + } + })?; + let mut depth = 1usize; + let mut separator_event = None; + for (index, event) in events.iter().enumerate().skip(start_event + 1) { + if event.position > limit { + break; + } + match &event.kind { + Event::MathRootStart { .. } => depth += 1, + Event::MathRootSeparator if depth == 1 && separator_event.is_none() => { + separator_event = Some(index); + } + Event::MathRootEnd if depth == 1 => { + let separator_event = separator_event?; + return Some(MathRootSpan { + has_index, + radical, + math_fonts, + start_event, + separator_event, + end_event: index, + separator_position: events[separator_event].position, + end_position: event.position, + location, + }); + } + Event::MathRootEnd => depth -= 1, + _ => {} + } + } + None +} + +fn find_math_delimiter_span( + events: &[tex_expansion::FrontendEvent], + start_position: usize, + limit: usize, + search_after: usize, +) -> Option { + use tex_expansion::FrontendEventKind as Event; + + let (start_event, left, left_settings, location) = events + .iter() + .enumerate() + .skip(search_after) + .find_map(|(index, event)| { + if event.position != start_position { + return None; + } + match &event.kind { + Event::MathDelimiterStart { + delimiter, + settings, + } => Some((index, delimiter.clone(), *settings, event.location.clone())), + _ => None, + } + })?; + let mut depth = 1usize; + let mut middles = Vec::new(); + for (index, event) in events.iter().enumerate().skip(start_event + 1) { + if event.position > limit { + break; + } + match &event.kind { + Event::MathDelimiterStart { .. } => depth += 1, + Event::MathDelimiterMiddle { + delimiter, + settings, + } if depth == 1 => { + middles.push((delimiter.clone(), *settings, event.position, index)); + } + Event::MathDelimiterEnd { + delimiter, + settings, + } if depth == 1 => { + return Some(MathDelimiterSpan { + left, + left_settings, + right: delimiter.clone(), + right_settings: *settings, + middles, + start_event, + end_event: index, + end_position: event.position, + location, + }); + } + Event::MathDelimiterEnd { .. } => depth -= 1, + _ => {} + } + } + None +} + +fn find_math_choice_span( + events: &[tex_expansion::FrontendEvent], + start_position: usize, + limit: usize, + search_after: usize, +) -> Option { + use tex_expansion::FrontendEventKind as Event; + + let (start_event, location) = + events + .iter() + .enumerate() + .skip(search_after) + .find_map(|(index, event)| { + (event.position == start_position && matches!(&event.kind, Event::MathChoiceStart)) + .then(|| (index, event.location.clone())) + })?; + let mut nested_depth = 0usize; + let mut current_branch: Option<(MathStyleCommand, usize, usize)> = None; + let mut branches = Vec::with_capacity(4); + for (index, event) in events.iter().enumerate().skip(start_event + 1) { + if event.position > limit { + break; + } + match &event.kind { + Event::MathChoiceStart => nested_depth += 1, + Event::MathChoiceEnd if nested_depth > 0 => nested_depth -= 1, + Event::MathChoiceEnd => { + let (style, branch_event, branch_position) = current_branch?; + branches.push(MathChoiceBranchSpan { + style, + start_event: branch_event, + end_event: index, + start_position: branch_position, + end_position: event.position, + }); + if branches.len() != 4 { + return None; + } + return Some(MathChoiceSpan { + branches, + start_event, + end_event: index, + end_position: event.position, + location, + }); + } + Event::MathChoiceBranch(style) if nested_depth == 0 => { + if let Some((previous_style, branch_event, branch_position)) = current_branch { + branches.push(MathChoiceBranchSpan { + style: previous_style, + start_event: branch_event, + end_event: index, + start_position: branch_position, + end_position: event.position, + }); + } + current_branch = Some((*style, index, event.position)); + } + _ => {} + } + } + None +} + +fn find_math_container_end( + events: &[tex_expansion::FrontendEvent], + start_position: usize, + limit: usize, + fraction_search_after: usize, + root_search_after: usize, + delimiter_search_after: usize, + group_search_after: usize, + choice_search_after: usize, +) -> Option<(usize, usize)> { + let fraction = find_math_fraction_span(events, start_position, limit, fraction_search_after); + let root = find_math_root_span(events, start_position, limit, root_search_after); + let delimiter = find_math_delimiter_span(events, start_position, limit, delimiter_search_after); + let group = find_math_group_span(events, start_position, limit, group_search_after); + let choice = find_math_choice_span(events, start_position, limit, choice_search_after); + [ + fraction.map(|span| (span.start_event, span.end_position, span.end_event)), + root.map(|span| (span.start_event, span.end_position, span.end_event)), + delimiter.map(|span| (span.start_event, span.end_position, span.end_event)), + group.map(|span| (span.start_event, span.end_position, span.end_event)), + choice.map(|span| (span.start_event, span.end_position, span.end_event)), + ] + .into_iter() + .flatten() + .min_by_key(|(start_event, _, _)| *start_event) + .map(|(_, end_position, end_event)| (end_position, end_event)) +} + +fn read_math_argument_with_events( + expanded: &tex_expansion::ExpandedTokenStream, + range: &Range, + events: &[tex_expansion::FrontendEvent], + start: usize, + search_after: usize, +) -> Option<(Range, usize)> { + let mut argument_start = start; + while let Some(tex_expansion::ExpandedTokenValue::Space(character)) = + expanded.token_value_at(range.start + argument_start) + { + if !character.is_whitespace() { + break; + } + argument_start += character.len_utf8(); + } + + let absolute_start = range.start + argument_start; + if let Some((end_position, _)) = find_math_container_end( + events, + absolute_start, + range.end, + search_after, + search_after, + search_after, + search_after, + search_after, + ) { + return Some((absolute_start..end_position, end_position - range.start)); + } + + let end_position = expanded.token_item_at(absolute_start)?.end_position; + (end_position <= range.end) + .then_some((absolute_start..end_position, end_position - range.start)) +} + +fn parse_child_expression( + expanded: &tex_expansion::ExpandedTokenStream, + parent_events: &[tex_expansion::FrontendEvent], + range: Range, +) -> Result { + let events = events_for_range(parent_events, &range); + parse_math_expression_with_events(expanded, range, &events) +} + +fn events_for_range( + events: &[tex_expansion::FrontendEvent], + range: &Range, +) -> Vec { + events + .iter() + .filter(|event| range.start <= event.position && event.position <= range.end) + .cloned() + .collect() +} + +fn with_source( + expanded: &tex_expansion::ExpandedTokenStream, + range: Range, + expression: MathExpr, +) -> MathExpr { + MathExpr::Spanned { + location: expanded.source_at(range.start), + expression: Box::new(expression), + } +} + +pub fn split_math_cells( + expanded: &tex_expansion::ExpandedTokenStream, + range: Range, + separators: &[usize], +) -> Option>> { + if separators.is_empty() { + return None; + } + + let range_len = range.end - range.start; + let events = events_for_range(&expanded.events, &range); + let mut cells = Vec::with_capacity(separators.len() + 1); + let mut cell_start = 0usize; + let mut cursor = 0usize; + let mut separator_index = 0usize; + let mut fraction_search_after = 0usize; + let mut root_search_after = 0usize; + let mut delimiter_search_after = 0usize; + let mut group_search_after = 0usize; + let mut choice_search_after = 0usize; + + while cursor < range_len { + if let Some((end_position, end_event)) = find_math_container_end( + &events, + range.start + cursor, + range.end, + fraction_search_after, + root_search_after, + delimiter_search_after, + group_search_after, + choice_search_after, + ) { + cursor = end_position - range.start; + fraction_search_after = end_event + 1; + root_search_after = end_event + 1; + delimiter_search_after = end_event + 1; + group_search_after = end_event + 1; + choice_search_after = end_event + 1; + continue; + } + while separators + .get(separator_index) + .is_some_and(|separator| *separator < cursor) + { + separator_index += 1; + } + if separators.get(separator_index) == Some(&cursor) { + cells.push(cell_start..cursor); + cell_start = cursor; + separator_index += 1; + continue; + } + let absolute_cursor = range.start + cursor; + if let Some(token) = expanded.token_item_at(absolute_cursor) { + cursor = token.end_position - range.start; + } else { + cursor = expanded + .next_token_item_at_or_after(absolute_cursor + 1, range.end) + .map(|token| token.position - range.start) + .unwrap_or(range_len); + } + } + + while separators.get(separator_index) == Some(&range_len) { + cells.push(cell_start..range_len); + cell_start = range_len; + separator_index += 1; + } + cells.push(cell_start..range_len); + Some(cells) +} + +fn attach_math_script( + items: &mut Vec, + is_superscript: bool, + script: MathExpr, + location: Option, + limit_mode: Option, +) -> Result<(), String> { + let base = items.pop().unwrap_or_else(|| MathExpr::Text(String::new())); + let (base_location, base_expression) = unwrap_source(base); + let base = match base_expression { + MathExpr::Atom { + class: MathClass::Ordinary, + text, + math_family, + math_slots, + math_fonts, + } if text.chars().count() > 1 => { + let split_at = text.char_indices().last().map(|(index, _)| index).unwrap(); + let split_slot = text[..split_at].chars().count(); + let (base_math_slots, script_base_math_slots) = if math_family.is_some() { + ( + math_slots[..split_slot].to_vec(), + math_slots[split_slot..].to_vec(), + ) + } else { + (Vec::new(), Vec::new()) + }; + let split_location = base_location + .as_ref() + .map(|location| advance_location(location, text[..split_at].chars().count())); + items.push(with_location( + base_location.clone(), + MathExpr::Atom { + class: MathClass::Ordinary, + text: text[..split_at].to_string(), + math_family, + math_slots: base_math_slots, + math_fonts: Arc::clone(&math_fonts), + }, + )); + with_location( + split_location, + MathExpr::Atom { + class: MathClass::Ordinary, + text: text[split_at..].to_string(), + math_family, + math_slots: script_base_math_slots, + math_fonts, + }, + ) + } + base => with_location(base_location, base), + }; + let (base_location, base_expression) = unwrap_source(base); + let (base, mut sub, mut superscript, current_limit_mode) = match base_expression { + MathExpr::Script { + base, + sub, + superscript, + limits, + } => (base, sub, superscript, limits), + base => { + let limits = if matches!( + base, + MathExpr::Accent { + position: MathAccent::OverBrace | MathAccent::UnderBrace, + .. + } + ) { + MathLimitMode::Limits + } else { + MathLimitMode::Automatic + }; + ( + Box::new(with_location(base_location, base)), + None, + None, + limits, + ) + } + }; + if is_superscript { + if superscript.is_some() { + return Err(math_script_error(location.as_ref(), true)); + } + superscript = Some(Box::new(script)); + } else { + if sub.is_some() { + return Err(math_script_error(location.as_ref(), false)); + } + sub = Some(Box::new(script)); + } + let limit_mode = limit_mode.filter(|_| base.class() == MathClass::Operator); + let limits = limit_mode.unwrap_or(current_limit_mode); + items.push(with_location( + location, + MathExpr::Script { + base, + sub, + superscript, + limits, + }, + )); + Ok(()) +} + +fn math_script_error(location: Option<&SourceLocation>, is_superscript: bool) -> String { + let message = if is_superscript { + "Double superscript" + } else { + "Double subscript" + }; + math_parse_error(location, message) +} + +fn math_parse_error(location: Option<&SourceLocation>, message: &str) -> String { + let Some(location) = location else { + return message.to_string(); + }; + let origin = match &location.origin { + SourceOrigin::File(path) => path.display().to_string(), + SourceOrigin::Terminal => "".to_string(), + }; + format!("{origin}:{}:{}: {message}", location.line, location.column) +} + +fn append_math_text( + items: &mut Vec, + character: char, + class: MathClass, + math_family: Option, + math_slot: Option, + math_fonts: MathFontFamilies, + location: Option, +) { + if let Some(MathExpr::Spanned { + location: previous_location, + expression, + }) = items.last_mut() + { + if let MathExpr::Atom { + class: previous_class, + text, + math_family: previous_family, + math_slots, + math_fonts: previous_math_fonts, + } = expression.as_mut() + { + if *previous_class == class + && *previous_family == math_family + && **previous_math_fonts == *math_fonts + && math_slot_follows(math_family, math_slots.last().copied(), math_slot) + && locations_are_contiguous(previous_location.as_ref(), text, location.as_ref()) + { + text.push(character); + if let Some(slot) = math_slot { + math_slots.push(slot); + } + return; + } + } + } + items.push(with_location( + location, + MathExpr::Atom { + class, + text: character.to_string(), + math_family, + math_slots: math_slot.into_iter().collect(), + math_fonts, + }, + )); +} + +fn math_slot_follows(family: Option, previous_slot: Option, next_slot: Option) -> bool { + match (family, previous_slot, next_slot) { + (None, None, None) => true, + (Some(_), Some(previous), Some(next)) => previous.checked_add(1) == Some(next), + _ => false, + } +} + +fn force_math_family(expression: &mut MathExpr, from: u8, to: u8) { + match expression { + MathExpr::Spanned { expression, .. } => force_math_family(expression, from, to), + MathExpr::Styled { .. } => {} + MathExpr::Classified { body, .. } + | MathExpr::Phantom { body, .. } + | MathExpr::Accent { body, .. } => { + force_math_family(body, from, to); + } + MathExpr::Atom { math_family, .. } if *math_family == Some(from) => { + *math_family = Some(to); + } + MathExpr::Sequence(items) => { + for item in items { + force_math_family(item, from, to); + } + } + MathExpr::Alignment { rows, .. } => { + for item in rows.iter_mut().flatten() { + force_math_family(item, from, to); + } + } + MathExpr::Fraction { + numerator, + denominator, + .. + } => { + force_math_family(numerator, from, to); + force_math_family(denominator, from, to); + } + MathExpr::MathChoice { + display, + text, + script, + scriptscript, + } => { + force_math_family(display, from, to); + force_math_family(text, from, to); + force_math_family(script, from, to); + force_math_family(scriptscript, from, to); + } + MathExpr::Root { index, body, .. } => { + if let Some(index) = index { + force_math_family(index, from, to); + } + force_math_family(body, from, to); + } + MathExpr::Delimited { body, .. } => force_math_family(body, from, to), + MathExpr::Fenced { segments, .. } => { + for segment in segments { + force_math_family(segment, from, to); + } + } + MathExpr::Script { + base, + sub, + superscript, + .. + } => { + force_math_family(base, from, to); + if let Some(sub) = sub { + force_math_family(sub, from, to); + } + if let Some(superscript) = superscript { + force_math_family(superscript, from, to); + } + } + MathExpr::Text(_) + | MathExpr::TextStyled { .. } + | MathExpr::Atom { .. } + | MathExpr::SizedDelimiter { .. } + | MathExpr::UnicodeDelimiter { .. } + | MathExpr::MathStyleChange(_) + | MathExpr::MathSpacingChange(_) + | MathExpr::MathLineBreakPenaltiesChange(_) + | MathExpr::BreakPenalty(_) + | MathExpr::Space(_) + | MathExpr::Glue(_) + | MathExpr::Kern(_) => {} + } +} + +fn with_location(location: Option, expression: MathExpr) -> MathExpr { + MathExpr::Spanned { + location, + expression: Box::new(expression), + } +} + +fn append_math_scope( + items: &mut Vec, + expression: MathExpr, + location: Option, +) { + // Ordinary math braces scope TeX state but do not create an atom boundary. + let expression = match expression { + MathExpr::Spanned { expression, .. } => *expression, + expression => expression, + }; + if contains_math_style_change(&expression) { + let expression = match expression { + MathExpr::Sequence(_) => expression, + expression => MathExpr::Sequence(vec![expression]), + }; + items.push(with_location(location, expression)); + return; + } + match expression { + MathExpr::Sequence(mut group_items) => items.append(&mut group_items), + MathExpr::Text(text) if text.is_empty() => {} + MathExpr::TextStyled { text, .. } if text.is_empty() => {} + expression => items.push(expression), + } +} + +fn contains_math_style_change(expression: &MathExpr) -> bool { + match expression { + MathExpr::Spanned { expression, .. } => contains_math_style_change(expression), + MathExpr::MathStyleChange(_) => true, + MathExpr::Sequence(items) => items.iter().any(contains_math_style_change), + _ => false, + } +} + +fn unwrap_source(expression: MathExpr) -> (Option, MathExpr) { + match expression { + MathExpr::Spanned { + location, + expression, + } => (location, *expression), + expression => (None, expression), + } +} + +fn advance_location(location: &SourceLocation, characters: usize) -> SourceLocation { + let mut location = location.clone(); + location.column += characters; + location +} + +fn locations_are_contiguous( + previous: Option<&SourceLocation>, + previous_text: &str, + next: Option<&SourceLocation>, +) -> bool { + match (previous, next) { + (None, None) => true, + (Some(previous), Some(next)) => { + previous.origin == next.origin + && previous.line == next.line + && previous.column + previous_text.chars().count() == next.column + } + _ => false, + } +} + +fn math_class_for_character(character: char) -> MathClass { + match character { + '+' | '−' | '-' | '±' | '∓' | '×' | '÷' | '⋅' | '·' | '∪' | '∩' => { + MathClass::Binary + } + '=' | '<' | '>' | '≤' | '≥' | '≠' | '≈' | '≃' | '∼' | ':' | '∈' | '∉' | '⊂' | '⊆' | '⊃' + | '⊇' | '→' | '←' | '⇒' | '⇔' | '↦' => MathClass::Relation, + '(' | '[' | '{' | '⟨' => MathClass::Opening, + ')' | ']' | '}' | '⟩' => MathClass::Closing, + ',' | ';' => MathClass::Punctuation, + '∑' | '∏' | '∫' | '∮' | '⋃' | '⋂' | '⋁' | '⋀' => MathClass::Operator, + _ => MathClass::Ordinary, + } +} + +fn math_code_properties( + character: char, + math_code: Option, + active_math_family: Option, +) -> (MathClass, Option, Option) { + let Some(code) = math_code.filter(|code| character.is_ascii() || *code != 0) else { + return (math_class_for_character(character), None, None); + }; + let math_class = (code >> 12) & 0x7; + let class = match math_class { + 1 => MathClass::Operator, + 2 => MathClass::Binary, + 3 => MathClass::Relation, + 4 => MathClass::Opening, + 5 => MathClass::Closing, + 6 => MathClass::Punctuation, + 0 | 7 => MathClass::Ordinary, + _ => unreachable!("math code classes use three bits"), + }; + let math_family = if math_class == 7 { + active_math_family + .filter(|family| (0..=15).contains(family)) + .map(|family| family as u8) + .unwrap_or(((code >> 8) & 0xf) as u8) + } else { + ((code >> 8) & 0xf) as u8 + }; + (class, Some(math_family), Some((code & 0xff) as u8)) +} diff --git a/crates/texrra-core/src/math_style.rs b/crates/texrra-core/src/math_style.rs new file mode 100644 index 0000000..3222cc3 --- /dev/null +++ b/crates/texrra-core/src/math_style.rs @@ -0,0 +1,97 @@ +/// Explicit math-style command encountered in a TeX math list. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum MathStyleCommand { + Display, + Text, + Script, + ScriptScript, +} + +/// TeX's eight math styles, including the cramped variants. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum MathStyle { + Display, + DisplayCramped, + Text, + TextCramped, + Script, + ScriptCramped, + ScriptScript, + ScriptScriptCramped, +} + +impl MathStyle { + pub fn from_command(command: MathStyleCommand) -> Self { + match command { + MathStyleCommand::Display => Self::Display, + MathStyleCommand::Text => Self::Text, + MathStyleCommand::Script => Self::Script, + MathStyleCommand::ScriptScript => Self::ScriptScript, + } + } + + pub fn cramped(self) -> Self { + match self { + Self::Display | Self::DisplayCramped => Self::DisplayCramped, + Self::Text | Self::TextCramped => Self::TextCramped, + Self::Script | Self::ScriptCramped => Self::ScriptCramped, + Self::ScriptScript | Self::ScriptScriptCramped => Self::ScriptScriptCramped, + } + } + + pub fn numerator_child(self) -> Self { + match self { + Self::Display => Self::Text, + Self::DisplayCramped => Self::TextCramped, + Self::Text => Self::Script, + Self::TextCramped => Self::ScriptCramped, + Self::Script => Self::ScriptScript, + Self::ScriptCramped => Self::ScriptScriptCramped, + Self::ScriptScript | Self::ScriptScriptCramped => self, + } + } + + pub fn denominator_child(self) -> Self { + self.numerator_child().cramped() + } + + pub fn superscript_child(self) -> Self { + match self { + Self::Display | Self::Text => Self::Script, + Self::DisplayCramped | Self::TextCramped => Self::ScriptCramped, + Self::Script | Self::ScriptScript => Self::ScriptScript, + Self::ScriptCramped | Self::ScriptScriptCramped => Self::ScriptScriptCramped, + } + } + + pub fn subscript_child(self) -> Self { + self.superscript_child().cramped() + } + + pub fn is_cramped(self) -> bool { + matches!( + self, + Self::DisplayCramped + | Self::TextCramped + | Self::ScriptCramped + | Self::ScriptScriptCramped + ) + } + + pub fn is_display(self) -> bool { + matches!(self, Self::Display | Self::DisplayCramped) + } + + pub fn is_text_size(self) -> bool { + matches!( + self, + Self::Display | Self::DisplayCramped | Self::Text | Self::TextCramped + ) + } + + pub fn conditional_math_spacing(self) -> bool { + self.is_text_size() + } +} diff --git a/crates/texrra-core/src/mouth.rs b/crates/texrra-core/src/mouth.rs new file mode 100644 index 0000000..5ca7e3b --- /dev/null +++ b/crates/texrra-core/src/mouth.rs @@ -0,0 +1,553 @@ +use std::collections::HashMap; + +use crate::{CatCode as EngineCatCode, EngineTokenValue}; + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct CatCodeTable { + low: Vec, + high: HashMap, + end_line_char: i32, + groups: Vec, +} + +#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] +struct CatCodeGroup { + catcodes: HashMap>, + end_line_char: Option, +} + +impl CatCodeTable { + pub fn latex_defaults() -> Self { + let mut table = Self { + low: EngineCatCode::PLAIN_TEX_DEFAULTS.to_vec(), + high: HashMap::new(), + end_line_char: '\r' as i32, + groups: Vec::new(), + }; + // LaTeX class and package files are read with `@` as a letter. The + // engine keeps that convention for every source so that `\@foo` + // commands tokenize as single control sequences; ordinary text + // containing `@` is unaffected because letter characters still print. + table.low['@' as usize] = EngineCatCode::Letter; + table + } + + pub fn assign(&mut self, index: usize, catcode: EngineCatCode, global: bool) { + self.prepare_assignment(index, global); + *self.get_index_mut_ref(index) = catcode; + } + + pub fn get(&self, character: char) -> EngineCatCode { + self.get_index(character as usize) + } + + pub fn get_index(&self, index: usize) -> EngineCatCode { + *self.get_index_ref(index) + } + + pub fn get_index_ref(&self, index: usize) -> &EngineCatCode { + self.low + .get(index) + .or_else(|| self.high.get(&index)) + .unwrap_or(&EngineCatCode::Other) + } + + pub fn get_index_mut_ref(&mut self, index: usize) -> &mut EngineCatCode { + if let Some(catcode) = self.low.get_mut(index) { + return catcode; + } + self.high.entry(index).or_insert(EngineCatCode::Other) + } + + pub fn prepare_assignment(&mut self, index: usize, global: bool) { + if global { + for group in &mut self.groups { + group.catcodes.remove(&index); + } + } else if !self.groups.is_empty() { + let previous = self.stored_value(index); + self.groups + .last_mut() + .expect("catcode group exists") + .catcodes + .entry(index) + .or_insert(previous); + } + } + + pub fn begin_group(&mut self) { + self.groups.push(CatCodeGroup::default()); + } + + pub fn end_group(&mut self) { + let Some(group) = self.groups.pop() else { + return; + }; + for (index, value) in group.catcodes { + self.set_index(index, value); + } + if let Some(end_line_char) = group.end_line_char { + self.end_line_char = end_line_char; + } + } + + /// XeTeX disables `\endlinechar` outside the 8-bit character range. + pub fn end_line_char(&self) -> Option { + u32::try_from(self.end_line_char) + .ok() + .filter(|value| *value <= 255) + .and_then(char::from_u32) + } + + pub fn end_line_char_value(&self) -> &i32 { + &self.end_line_char + } + + pub fn end_line_char_value_mut_ref(&mut self, global: bool) -> &mut i32 { + self.save_end_line_char_scope(global); + &mut self.end_line_char + } + + pub fn assign_end_line_char(&mut self, value: i32, global: bool) { + self.save_end_line_char_scope(global); + self.end_line_char = value; + } + + fn save_end_line_char_scope(&mut self, global: bool) { + if global { + for group in &mut self.groups { + group.end_line_char = None; + } + } else if let Some(group) = self.groups.last_mut() { + group.end_line_char.get_or_insert(self.end_line_char); + } + } + + fn stored_value(&self, index: usize) -> Option { + self.low + .get(index) + .copied() + .or_else(|| self.high.get(&index).copied()) + } + + fn set_index(&mut self, index: usize, value: Option) { + if let Some(catcode) = self.low.get_mut(index) { + if let Some(value) = value { + *catcode = value; + } + return; + } + match value { + Some(catcode) => { + self.high.insert(index, catcode); + } + None => { + self.high.remove(&index); + } + } + } +} + +impl Default for CatCodeTable { + fn default() -> Self { + Self::latex_defaults() + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct SourceSpan { + pub start: usize, + pub end: usize, + pub line: usize, + pub column: usize, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Token { + pub value: EngineTokenValue, + pub span: SourceSpan, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct InvalidCharacter { + pub value: char, + pub span: SourceSpan, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ScannerState { + NewLine, + MidLine, + SkipBlanks, +} + +#[derive(Clone, Copy, Debug)] +struct InputChar { + value: char, + span: SourceSpan, +} + +#[derive(Debug)] +struct InputLine { + chars: Vec, + position: usize, +} + +#[derive(Clone, Copy, Debug)] +struct RawChar { + input: InputChar, + catcode: EngineCatCode, +} + +pub struct Mouth { + source: String, + next_line_start: usize, + next_line_number: usize, + current_line: Option, + finished: bool, + state: ScannerState, + pending: Option, +} + +impl Mouth { + pub fn new(source: &str) -> Self { + Self { + source: source.to_string(), + next_line_start: 0, + next_line_number: 1, + current_line: None, + finished: false, + state: ScannerState::NewLine, + pending: None, + } + } + + pub fn next_token( + &mut self, + catcodes: &CatCodeTable, + ) -> Result, InvalidCharacter> { + if let Some(token) = self.pending.take() { + return Ok(Some(token)); + } + + loop { + let Some(raw) = self.next_raw(catcodes) else { + return Ok(None); + }; + let character = raw.input.value; + let token = match raw.catcode { + EngineCatCode::Escape => { + let (name, state, end) = self.read_control_sequence(raw.input, catcodes); + self.state = state; + Token { + value: EngineTokenValue::ControlSequence(name), + span: SourceSpan { + end, + ..raw.input.span + }, + } + } + EngineCatCode::EndOfLine => { + self.end_current_line(); + let token = match self.state { + ScannerState::NewLine => Token { + value: EngineTokenValue::ControlSequence("par".to_string()), + span: raw.input.span, + }, + ScannerState::MidLine => Token { + value: EngineTokenValue::Character { + value: ' ', + catcode: EngineCatCode::Space, + }, + span: raw.input.span, + }, + ScannerState::SkipBlanks => continue, + }; + self.state = ScannerState::NewLine; + token + } + EngineCatCode::Space => match self.state { + ScannerState::NewLine | ScannerState::SkipBlanks => continue, + ScannerState::MidLine => { + self.state = ScannerState::SkipBlanks; + Token { + value: EngineTokenValue::Character { + value: ' ', + catcode: EngineCatCode::Space, + }, + span: raw.input.span, + } + } + }, + EngineCatCode::BeginGroup + | EngineCatCode::EndGroup + | EngineCatCode::MathShift + | EngineCatCode::AlignmentTab + | EngineCatCode::Parameter + | EngineCatCode::Subscript + | EngineCatCode::Letter + | EngineCatCode::Other => { + self.state = ScannerState::MidLine; + Token { + value: EngineTokenValue::Character { + value: character, + catcode: raw.catcode, + }, + span: raw.input.span, + } + } + EngineCatCode::Superscript => { + if self.maybe_apply_caret_notation(character, true) { + continue; + } + self.state = ScannerState::MidLine; + Token { + value: EngineTokenValue::Character { + value: character, + catcode: raw.catcode, + }, + span: raw.input.span, + } + } + EngineCatCode::Active => { + self.state = ScannerState::MidLine; + Token { + value: EngineTokenValue::Active(character), + span: raw.input.span, + } + } + EngineCatCode::Comment => { + self.end_current_line(); + continue; + } + EngineCatCode::Ignored => continue, + EngineCatCode::Invalid => { + return Err(InvalidCharacter { + value: character, + span: raw.input.span, + }); + } + }; + return Ok(Some(token)); + } + } + + pub fn unread_token(&mut self, token: Token) { + debug_assert!(self.pending.is_none()); + self.pending = Some(token); + } + + fn next_raw(&mut self, catcodes: &CatCodeTable) -> Option { + loop { + let line_is_exhausted = self + .current_line + .as_ref() + .is_none_or(|line| line.position >= line.chars.len()); + if line_is_exhausted { + self.state = ScannerState::NewLine; + if !self.start_new_line(catcodes) { + return None; + } + } + + let line = self.current_line.as_mut()?; + let input = *line.chars.get(line.position)?; + line.position += 1; + return Some(RawChar { + input, + catcode: catcodes.get(input.value), + }); + } + } + + fn start_new_line(&mut self, catcodes: &CatCodeTable) -> bool { + if self.finished || self.source.is_empty() || self.next_line_start >= self.source.len() { + self.finished = true; + return false; + } + + let start = self.next_line_start; + let (source_end, next_line_start) = match self.source[start..].find('\n') { + Some(offset) => (start + offset, start + offset + 1), + None => (self.source.len(), self.source.len()), + }; + let has_line_feed = next_line_start > source_end; + let line_number = self.next_line_number; + let mut chars = Vec::new(); + let mut column = 1; + for (byte_offset, value) in self.source[start..source_end].char_indices() { + let absolute_start = start + byte_offset; + let mut end = absolute_start + value.len_utf8(); + if value == '\r' && has_line_feed && end == source_end { + end = next_line_start; + } + chars.push(InputChar { + value, + span: SourceSpan { + start: absolute_start, + end, + line: line_number, + column, + }, + }); + column += 1; + } + while chars.last().is_some_and(|character| character.value == ' ') { + chars.pop(); + } + let end_of_trimmed_source = chars.last().map_or(start, |character| { + character.span.start + character.value.len_utf8() + }); + if let Some(end_line_char) = catcodes.end_line_char() { + chars.push(InputChar { + value: end_line_char, + span: SourceSpan { + start: end_of_trimmed_source, + end: next_line_start, + line: line_number, + column: chars.len() + 1, + }, + }); + } + + self.current_line = Some(InputLine { chars, position: 0 }); + self.next_line_start = next_line_start; + self.next_line_number += 1; + true + } + + fn end_current_line(&mut self) { + if let Some(line) = &mut self.current_line { + line.position = line.chars.len(); + } + } + + fn read_control_sequence( + &mut self, + escape: InputChar, + catcodes: &CatCodeTable, + ) -> (String, ScannerState, usize) { + let first = loop { + let Some(first) = self.next_raw(catcodes) else { + return (String::new(), ScannerState::NewLine, escape.span.end); + }; + if first.catcode == EngineCatCode::Superscript + && self.maybe_apply_caret_notation(first.input.value, true) + { + continue; + } + break first; + }; + + let mut name = String::new(); + name.push(first.input.value); + if first.catcode == EngineCatCode::Letter { + loop { + let Some(next) = self.peek_raw(catcodes) else { + break; + }; + if next.catcode == EngineCatCode::Superscript + && self.maybe_apply_caret_notation(next.input.value, false) + { + continue; + } + if next.catcode != EngineCatCode::Letter { + break; + } + let next = self + .next_raw(catcodes) + .expect("peeked input character exists"); + name.push(next.input.value); + } + } + let state = match first.catcode { + EngineCatCode::Letter | EngineCatCode::Space => ScannerState::SkipBlanks, + _ => ScannerState::MidLine, + }; + let end = self.last_consumed_end().unwrap_or(first.input.span.end); + (name, state, end.max(escape.span.end)) + } + + fn peek_raw(&mut self, catcodes: &CatCodeTable) -> Option { + let line_is_exhausted = self + .current_line + .as_ref() + .is_none_or(|line| line.position >= line.chars.len()); + if line_is_exhausted { + return None; + } + let line = self.current_line.as_ref()?; + let input = *line.chars.get(line.position)?; + Some(RawChar { + input, + catcode: catcodes.get(input.value), + }) + } + + fn last_consumed_end(&self) -> Option { + let line = self.current_line.as_ref()?; + line.position + .checked_sub(1) + .and_then(|index| line.chars.get(index)) + .map(|input| input.span.end) + } + + fn maybe_apply_caret_notation(&mut self, caret: char, caret_consumed: bool) -> bool { + let Some(line) = &mut self.current_line else { + return false; + }; + let first_caret_index = if caret_consumed { + line.position.checked_sub(1) + } else { + Some(line.position) + }; + let Some(first_caret_index) = first_caret_index else { + return false; + }; + let second_caret_index = first_caret_index + 1; + let third_character_index = second_caret_index + 1; + let (Some(first), Some(second), Some(third)) = ( + line.chars.get(first_caret_index), + line.chars.get(second_caret_index), + line.chars.get(third_character_index), + ) else { + return false; + }; + if first.value != caret || second.value != caret { + return false; + } + + line.position = third_character_index; + let Some(byte) = u8::try_from(third.value as u32).ok().filter(u8::is_ascii) else { + return true; + }; + let transformed = match byte { + 0x00..=0x3f => byte + 0x40, + 0x40..=0x7f => byte - 0x40, + _ => return true, + }; + if let Some(character) = char::from_u32(u32::from(transformed)) { + if let Some(input) = line.chars.get_mut(third_character_index) { + input.value = character; + } + } + true + } +} + +impl Token { + pub fn control_sequence(&self) -> Option<&str> { + match &self.value { + EngineTokenValue::ControlSequence(name) => Some(name), + _ => None, + } + } + + pub fn character(&self) -> Option<(char, EngineCatCode)> { + match self.value { + EngineTokenValue::Character { value, catcode } => Some((value, catcode)), + EngineTokenValue::Active(value) => Some((value, EngineCatCode::Active)), + EngineTokenValue::ControlSequence(_) => None, + } + } +} diff --git a/crates/texrra-core/src/references.rs b/crates/texrra-core/src/references.rs new file mode 100644 index 0000000..817636f --- /dev/null +++ b/crates/texrra-core/src/references.rs @@ -0,0 +1,90 @@ +use std::collections::HashMap; + +use crate::document::{Block, 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 resolve_runs( + runs: &mut [Run], + labels: &HashMap, + citations: &HashMap, + ) { + for run in runs { + let Some(reference) = run.unresolved_reference.take() else { + continue; + }; + run.text = match reference { + UnresolvedReference::Label(key) => labels + .get(&key) + .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::>() + .join(", "); + format!("[{formatted}]") + } + }; + } + } + + fn resolve_list( + list: &mut ListBlock, + labels: &HashMap, + citations: &HashMap, + ) { + for item in &mut list.items { + resolve_runs(&mut item.runs, labels, citations); + for nested in &mut item.nested { + resolve_list(nested, labels, citations); + } + } + } + + let labels = &document.labels; + let citations = &document.citations; + for block in &mut document.blocks { + match block { + Block::Paragraph(runs) | Block::Heading { runs, .. } => { + resolve_runs(runs, labels, citations) + } + Block::List(list) => resolve_list(list, labels, citations), + Block::Table { rows, caption, .. } => { + for cell in rows.iter_mut().flatten() { + resolve_runs(cell, labels, citations); + } + if let Some(caption) = caption { + resolve_runs(caption, labels, citations); + } + } + Block::Image { caption, .. } => { + if let Some(caption) = caption { + resolve_runs(caption, labels, citations); + } + } + Block::FramedBox { runs, .. } | Block::Centered { runs } => { + resolve_runs(runs, labels, citations) + } + Block::Bibliography(items) => { + for (_, runs) in items { + resolve_runs(runs, labels, citations); + } + } + Block::HorizontalRule { .. } + | Block::Math { .. } + | Block::VerticalKern(_) + | Block::VerticalGlue(_) + | Block::Penalty(_) + | Block::PageBreak => {} + } + } + document +} diff --git a/crates/texrra-core/src/source.rs b/crates/texrra-core/src/source.rs new file mode 100644 index 0000000..4e66637 --- /dev/null +++ b/crates/texrra-core/src/source.rs @@ -0,0 +1,16 @@ +use std::path::PathBuf; + +/// Where a TeX source location originated. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum SourceOrigin { + File(PathBuf), + Terminal, +} + +/// A one-based source position owned independently of a runtime adapter. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct SourceLocation { + pub origin: SourceOrigin, + pub line: usize, + pub column: usize, +} diff --git a/crates/texrra-core/src/state.rs b/crates/texrra-core/src/state.rs new file mode 100644 index 0000000..a3ae1c4 --- /dev/null +++ b/crates/texrra-core/src/state.rs @@ -0,0 +1,74 @@ +use crate::{ + EngineCommandName, + assignment_scope::AssignmentScope, + command::{EngineCommandMeaning, NativeCommandTable}, + environment::EnvironmentStack, + macros::MacroTable, + math_code::{DelimiterCodeTable, MathCodeTable, UnicodeMathCodeTable}, + mouth::CatCodeTable, +}; + +/// Mutable TeX language state shared across tokenization and execution phases. +/// +/// Runtime adapters may hold this state, but the values and group semantics are +/// owned by the Rust engine core. +#[derive(Default, serde::Serialize, serde::Deserialize)] +pub struct EngineSemanticState { + pub catcodes: CatCodeTable, + pub math_codes: MathCodeTable, + pub unicode_math_codes: UnicodeMathCodeTable, + pub delimiter_codes: DelimiterCodeTable, + pub assignment_scope: AssignmentScope, + pub pending_global_assignment: bool, + pub environments: EnvironmentStack, + pub macros: MacroTable, + #[serde(default)] + pub native_commands: NativeCommandTable, + group_depth: usize, +} + +impl EngineSemanticState { + /// Resolve a control sequence using engine-owned macro and primitive meanings. + pub fn command_meaning(&self, name: &EngineCommandName) -> Option { + if self.macros.get(name).is_some() { + Some(EngineCommandMeaning::Macro) + } else { + self.native_commands + .get(name) + .map(EngineCommandMeaning::Native) + } + } + + pub fn begin_group(&mut self) { + self.group_depth += 1; + self.catcodes.begin_group(); + self.math_codes.begin_group(); + self.unicode_math_codes.begin_group(); + self.delimiter_codes.begin_group(); + self.assignment_scope.begin_group(); + self.macros.begin_group(); + self.native_commands.begin_group(); + } + + pub fn end_group(&mut self) { + self.group_depth = self.group_depth.saturating_sub(1); + self.catcodes.end_group(); + self.math_codes.end_group(); + self.unicode_math_codes.end_group(); + self.delimiter_codes.end_group(); + self.assignment_scope.end_group(); + self.macros.end_group(); + self.native_commands.end_group(); + } + + pub fn is_safe_document_checkpoint(&self) -> bool { + if self.group_depth != 0 { + return false; + } + match self.environments.as_slice() { + [] => true, + [environment] => environment == "document", + _ => false, + } + } +} diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 0000000..df57d92 --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,72 @@ +# Roadmap: remaining structural work + +This file lists the concrete implementation plans for the foundational items that +are still missing. Each item names the files/functions to touch. + +## 1. Paragraph indentation (`\parindent`) + +- Add `parindent: Scaled` to `DocumentModel` (with the 11pt article default 17pt) + and a `Parindent` frontend event. +- Feed `\setlength{\parindent}{...}` through an **engine-side named length + register** (the adapter already stores named lengths); when the register is + written, emit the event. Do not use a prelude `\ifx` conditional: it broke + preamble loading when tried. +- Apply indentation inside the paragraph breaker: the first line's available + width is `line_width - parindent` and its start x is `parindent`. + `boxworks_line_break` / `cached_paragraph_lines` currently take only a width; + extend the signature with a first-line indent and carry the per-line x offset + into `text_layout::LineBox`/`PositionedLine.x`. +- Suppress after headings, after `\maketitle`, and for `\noindent`; track a + `suppress_indent` flag in the parser. + +## 2. Sans family (`\sffamily`) + +- Load Liberation Sans in `latin_dir` alongside serif/mono (see + `font_inputs`/`register_box_font_family` in `src/rust_typeset/pdf.rs`). +- Add `sans: bool` to `Run` and to the style map key; `paragraph_font_id` + selects the sans family when set. +- Thread a `sans_family` through `TextLine`/`TextLine::new` and the SVG + font-family choice (`TexrraSans`), and add a `@font-face` in the preview. +- `\sffamily`/`\textsf{...}` become declaration primitives like + `\ttfamily`. + +## 3. Inline framed boxes / `\raisebox` + +- Add `y_offset: Mm` to `PositionedSpan` and `PositionedRule`; PDF/SVG painters + add it to the baseline. +- Represent inline boxes as a nested `LineItem::Box { items, width, ascent, + depth, inset, raise, frame }`; the line breaker measures the content once and + advances by its width. +- Paint child items at `x + inset`, baseline `- raise`; draw frame rules at the + box rectangle when `frame` is set. +- `\raisebox{lift}{...}` reuses the same nested item with `raise = lift`. + +## 4. Footnotes + +- Parser: capture `\footnote{...}`/`\thanks{...}` into a per-paragraph list + with a number marker run (superscript approximation via smaller raised text + once y offsets exist). +- Page model: add a footnote area to the page goal; the planner must reduce the + text height and place footnotes with a separator rule at the bottom. +- Paint footnotes as normal positioned lines after the page's content. + +## 5. Floats + +- Classify figure/table blocks as floats with `[htbp]` placement hints. +- Planner: maintain pending floats and try top/bottom/page placements; keep + reading order for text and defer floats when they do not fit. +- Renderer: place deferred floats at the saved slots; page keys must include + float placement decisions. + +## 6. Page styles / headers-footers + +- `DocumentModel` fields for header/footer runs and `\pagestyle`/`\thispagestyle`. +- Paint headers/footers in the page margins in both PDF and SVG; page numbers + need a page index placeholder resolved at paint time. + +## 7. Unified pagination + +- Extract the current duplicated planner (`build_page_break_plan`) and renderer + (`build_positioned_pages`) vertical logic into one page builder returning an + ordered list of placed items, then use it for both page-break decisions and + final painting. diff --git a/docs/STATUS.md b/docs/STATUS.md new file mode 100644 index 0000000..dfed1a9 --- /dev/null +++ b/docs/STATUS.md @@ -0,0 +1,56 @@ +# Engine status + +The project is split into two repositories: `texrra-engine` (this Rust engine +and HTTP server) and `texrra-web` (the static editor frontend). The engine +discovers the frontend through `TEXRRA_WEB_DIR`, `../web`, or `./web`. + +Rust-native, Typst-inspired incremental LaTeX engine. No external XeLaTeX is +invoked. The live server keeps compiled documents cached and only rebuilds when +the source changes; the SVG preview is refreshed per page. + +## Implemented + +- Headings: numbered `\section`/`\subsection`/`\subsubsection` and starred + `\section*` variants (starred headings do not advance the counter). +- Box material: `\rule` (raise/width/height), block `\fbox`, `\parbox`, + inline `\mbox`/`\makebox`, `center`, `\hrule` with `width`/`height`. +- Fonts: Liberation Serif/Mono faces, bold/italic/monospace declarations with + group scoping, grouped text-style commands, uppercase small-caps approximation. +- Paragraphs: Knuth-Plass breaking, TeX hyphenation patterns, justification, + centering. +- Pages: A4/A5/B5/Letter/Legal/Executive, landscape, geometry margins and + text block, automatic pagination, `\newpage`/`\pagebreak`. +- Classes/packages: built-in classes, local `.cls`/`.sty`, paper options, + `\DeclareOption`/`\ProcessOptions`/`\ExecuteOptions`/option passing. +- Compatibility: spacing macros (quad/qquad/thin/en/med/thick, `\vspace*`, + `\hspace*`, skips), text symbols/letters/punctuation, break advisories, + metadata, citations/references, tables/lists/images. +- Live preview: paragraph and page-layout caches, page-hash diffing, warm + rebuilds in the low milliseconds for small edits. + +## Remaining structural work + +See `docs/ROADMAP.md` for concrete implementation plans. + +## Known approximations / gaps + +- Paragraphs: no `\parindent` indentation (a parse-side kern experiment did not + take effect and a `\setlength` conditional broke the preamble, so it was + reverted) and no `\hfill` (last-line infinite glue is not stretched). +- Fonts: no sans family (`\sffamily` is a no-op); small caps are uppercase-only. +- Boxes: `\fbox`/`\parbox` are block-level (an inline `\fbox` starts a block); + `\raisebox`, `\minipage`, and VBox material are missing. +- Pages: no footnote insertion area, no floats, no headers/footers (fancyhdr + commands are accepted as no-ops), planner and renderer are separate. +- Lengths: `\textwidth`/`\textheight`/`\linewidth`/`\columnwidth` are fixed + A4-content defaults, not geometry-aware. +- Miscellaneous: `\tableofcontents`/list commands are no-ops; base font-size + class options (10/11/12pt) are parsed but unused; rules are painted with 1x1 + images in PDF. + +## Verification + +- `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to + one A4 page each; the arXiv template project compiles to 3 Letter pages. +- `cargo fmt --check` passes; `cargo test` currently has no test cases. +- Warm preview: hello ~11ms, arXiv ~15ms (release server). diff --git a/docs/compiler-architecture.md b/docs/compiler-architecture.md new file mode 100644 index 0000000..d292a65 --- /dev/null +++ b/docs/compiler-architecture.md @@ -0,0 +1,1144 @@ +# Rust-native LaTeX compiler direction + +## Goal + +Build a Rust compiler whose output follows XeTeX/LaTeX behavior closely, while +making edits cheap to recompile and keeping the PDF preview tied to the same +layout result. XeTeX behavior is the compatibility target; invoking XeLaTeX is +not part of the Rust compiler. + +XeTeX's source is the primary reference for the engine rewrite: its algorithms +and observable behavior are being reimplemented in Rust, with no XeLaTeX +subprocess in the product. The legacy source tree does not need to dictate the +Rust module boundaries. LaTeX is a macro format and package ecosystem layered +on the TeX engine, and a rendered document also depends on fonts, font shaping, +file lookup, and PDF output; compatibility has to cover those layers as well. + +## Stage model + +Typst documents four main stages: parsing, evaluation, layout, and export. It +also reuses prior work through incremental parsing and memoized evaluation and +layout. This compiler adopts the same separation while retaining TeX's mutable +macro expansion and box/glue layout model. See the [Typst compiler +architecture](https://github.com/typst/typst/blob/main/docs/dev/architecture.md). + +1. **World and source inputs** resolve the main `.tex` file, `\input`, local + `.sty` and `.bib` files, images, fonts, and compiler settings. The world + records dependencies so edits can invalidate their dependents. +2. **Tokenization and expansion** preserve TeX tokens, source spans, grouping, + category codes, and macro state. Expansion produces syntax that later passes + can inspect without throwing away source locations. +3. **Document interpretation** builds a semantic document tree for paragraphs, + math, tables, floats, labels, references, and bibliography entries. Cross + references and bibliography resolution run as explicit passes. +4. **Layout** converts semantic content into TeX-style boxes, glue, penalties, + and page frames. Paragraph breaking and page building operate on those + structures. Math uses the same box model, including stacked fractions and + script placement. +5. **Export** turns final page frames into PDF. Other views, if added, consume + the same frames rather than implementing a second approximation of layout. + +## Incremental compilation + +The editor sends the complete source after a debounce. Preprocessing, +math lowering, semantic parsing, and PDF generation still visit the full +document. For cacheable documents, expansion can resume from the latest safe +body checkpoint whose input prefix is unchanged; other edits reuse the +preamble checkpoint or take the full expansion path. Paragraph and math caches +reuse unchanged layout results. Body and preamble VM snapshots are retained +only after TeX groups and environments are safe and the Rust input stack has no +pending source or macro replacement frames. Page breaking can retain stable page-start +anchors before the earliest changed block when the page geometry and fonts are +unchanged; each break also records how far its look-ahead reached, so edits +that touch that range invalidate the dependent page. Line placement and PDF +output are still rebuilt for the full document. Rich paragraph parsing now keys +on normalized token/event sequences with offsets relative to each paragraph; +cached math runs are refreshed from the current math events so a preceding edit +does not retain stale source locations. +Typst's architecture shows why deeper incremental behavior needs stable source +identities and cached phase results, not just a timer. This compiler should +retain a compilation session with: + +- parsed regions keyed by source file and stable source spans; +- expansion results keyed by the input region and the macro/environment state + that reaches it; +- layout results keyed by semantic nodes, font metrics, and inherited layout + settings; +- dependency edges for references, bibliography entries, images, styles, and + fonts, so an edit invalidates the affected results. + +TeX state means a change can affect more than the edited paragraph. For example, +a macro definition can invalidate later uses, while a changed label can affect +references elsewhere. The dependency graph must model those cases before the +compiler can safely reuse cached results. + +## Current implementation + +The `/compile` endpoint now calls the Rust implementation directly. The +pipeline preserves `\usepackage` and `\RequirePackage` in the TeX input +stream; the Rust VM loads supported local style files when those commands are +executed. `\newcommand`, `\renewcommand`, `\providecommand`, `\def`, and +`\gdef` use an engine-owned macro table and Rust argument substitution. +The shared `texrra-core` crate owns category-code and math-code values, +engine token values, source origins and locations, control-sequence names, macro definitions, parameter +matching, replacement instantiation, scoped macro tables, and the native +command-meaning table independently of Texlang's interned IDs. `engine::token`, +`engine::command`, `engine::macros`, and `engine::expansion` are compatibility +re-exports at the application boundary. +Texlang's temporary variable adapter re-exports the shared category-code and +math-code types. +`texrra-core::math_code::MathCodeTable`, `texrra-core::math_code::UnicodeMathCodeTable`, and +`texrra-core::math_code::DelimiterCodeTable` store the ordinary and Unicode math classifications and +delimiter registrations read by the Rust math frontend. Engine group hooks now +save and restore their local and global assignments; the Texlang variable +adapter does not maintain a second save stack for them. The compiler's +standard-component adapter omits the duplicate Texlang catcode, math-code, and +end-line-character state; its primitive map binds `\\catcode`, `\\mathcode`, +and `\\endlinechar` directly to the engine tables. +`texrra-core::math_style` owns TeX's eight math styles and the rules for +cramped, numerator, denominator, superscript, and subscript styles. The parser +and current 2D math layout consume this shared semantic model. +`texrra-core::math_list` owns atom-list boundaries, nested-list context, +TeX's rule for normalizing binary operators at list boundaries, and its +eight-class inter-atom spacing table. It also selects `\\mathchoice` branches +and resolves leading/trailing atom classes across nested expressions. It +selects thin, medium, thick, or zero mu glue from the active math style and +current math-skip settings. Its inline-math planner carries style and spacing +state through a sequence, emits explicit glue and penalties, and selects +relation/binary break opportunities while suppressing conflicts with following +relations or explicit penalties. The application measures formula boxes, +converts planned mu glue to backend units, and passes the resulting nodes to +Knuth–Plass. +`texrra-core::math_expr::MathExpr` now owns the typed math expression tree, +including source locations, atom classification, style metadata, scripts, +fractions, delimiters, and alignments. It also classifies character-like, +single-glyph, and operator nuclei for script and limit layout. +`texrra-core::math_alphabet` selects Unicode math alphabets and transforms +ordinary atoms through nested math expressions; the font backend supplies only +glyph-availability queries. The parser and PDF/SVG layout consume this engine +IR, while glyph measurement, rasterization, painting, and the recursive box +adapter remain in the application. +`texrra-core::document` owns the semantic document IR: document metadata, +page margins, paragraphs, headings, lists, tables, images, bibliography, +math, vertical nodes, source anchors, and unresolved references. The +application's `document` module is a compatibility re-export. +`texrra-core::document_parser::parse_document` consumes the source-mapped +expanded token/event stream and builds that IR; the application parser module is +a compatibility re-export. Reference resolution then produces the final +engine-owned model, which both PDF and HTML consume. +`texrra-core::references::resolve` performs reference and citation +resolution over that IR after parsing has collected the document-wide label +and citation tables. `CompilerSession` invokes this core phase directly. +`texrra-core::expanded` owns source-mapped expanded items and typed frontend +events, and `texrra-core::math_parser` consumes that stream to build the +math expression tree. The application modules retain compatibility re-exports +while the layout and font backends remain application-owned. +`texrra-core::math_constants` reads OpenType MATH constants into a +design-unit model and selects fraction, script, operator-limit, radical, and +bar parameters, including XeTeX fallback values. The font backend converts +these em-based parameters to page units. `texrra-core::math_layout` owns +math-sequence style and spacing planning, measured child placement, +fraction-box placement, ordinary script vertical placement and horizontal +script-kern placement, display-limit geometry, radical-box geometry, delimiter +target sizing, ordinary delimited-box and fenced-row placement, accent +placement, and alignment-box geometry from measured child boxes and resolved +spacing. It also groups +display-math rows, sizes `multline`, and positions equation numbers around the +formula using measured tag metrics. The application supplies font measurements +and initial math-skip settings, converts core spacing to page units, and paints +the result. PDF glyph images are placed by their lower-left corner because +`genpdf::render::Area::add_image` uses printpdf's lower-left coordinate +convention; the math box stores upper-left positions, so the painter adds the +image height before drawing. SVG uses the upper-left position directly. +`texrra-core::math_glyph` selects math-atom glyph text and font preference, +returns the engine-owned atom slant, and interprets OpenType MATH per-glyph +italic corrections, top accent attachment points, and height-dependent +corner-kern selection. The application maps the slant into backend styles, +opens fonts, maps characters to glyph IDs, converts OpenType values into +engine-owned `MathGlyphMetrics` and kern tables, converts design units to page +units, and reads glyph bounds and outlines. Script-kern nucleus traversal and +Unicode math-alphabet character mapping are core decisions; font glyph +availability remains a backend query. For math sequences, the core resolves +per-item math styles, spacing settings, class boundaries, and child contexts, +then positions measured child boxes; the application measures the children and +converts the returned coordinates to PDF units. +Each `MathFontMetrics` snapshot shares a per-glyph cache keyed by font-byte +identity and character, avoiding repeated font-face parsing and kern-table +expansion during layout. +Delimiter glyph assembly and outline access remain in the application. +`texrra-core::macros` scans `\def` targets, parameter text, and grouped +replacement bodies through a generic token-stream interface, then parses +parameter prefixes, delimiters, and replacement references using engine token +values. `texrra-core::expansion` scans macro arguments and instantiates +replacements; `texrra-core::input::InputStack` keeps tokenized replacement +frames alongside source frames. The adapter suspends pending VM tokens below a +Rust macro frame and lazily converts the selected engine token at the VM +boundary. +`texrra-core::command::NativeCommandTable` owns the ported primitive +meanings and scoped aliases. Texlang tags only route those tokens into the +adapter. +`\let` copies +the current engine-owned macro meaning by consulting the Rust macro table. A VM +hook now consults that table before command-map lookup during normal expansion +and `expand_once`, so the engine table decides macro expansion. Command-map +entries remain as reflection markers for VM primitives that inspect meanings. +The shared expansion dispatcher has a stable built-in identity so incremental +VM checkpoints can serialize those markers while macro bodies remain in the +Rust engine table. +`\edef` and `\xdef` expand a bounded token list before storing the result in +that same table. Macro definitions, argument matching, and substitution use +engine-owned `EngineToken` values; the Texlang adapter converts tokens while +reading the unexpanded stream and converts the finished replacement before +queueing it. Texlang still supplies that cursor and expansion stack, plus the +remaining primitive expansion runtime. It emits an ordered, source-spanned +token/event stream that the parser turns +into a `ParsedDocument`. The pipeline resolves document references, lays out +the resolved model, and writes PDF through `genpdf`. +`EngineSemanticState::command_meaning` now resolves each control sequence as +an engine macro or a native primitive, with macros taking precedence; both VM +adapter hooks consult this shared resolution. The VM-facing `CompilerState` delegates TeX semantics to +`texrra-core::state::EngineSemanticState` through the application adapter. +The core owns catcodes, math codes, assignment scope, macro definitions, +environment nesting, native-command meanings, and their group save/restore. +The adapter retains source I/O and registers that still use Texlang types. +Texlang-specific VM execution now lives in `texlang_adapter.rs`; the +`tex_expansion` module is a compatibility facade used by the compiler stages. +Texlang still owns the main execution loop and fallback dispatch. Rust macro +and native primitive meanings resolve through the engine state, and +`texrra-core::command::NativeCommandTable` owns the meanings of the ported layout, +arithmetic, and prefix primitives. The pre-execution adapter consults this +table; Texlang tags only route the token into that adapter. Primitive aliases +created by `\\let` copy their Rust meaning and follow group scope, while macro +definitions remove any shadowed native meaning. This change does not claim +XeTeX compatibility. +`texrra-core::input` owns source and tokenized replacement frames plus the +TeX file-name scanner; +`engine::input` remains a compatibility re-export. The project-owned `\\input` +and `\\endinput` primitives use this stack. Filename parsing follows XeTeX's +`more_name` and `scan_file_name`; the adapter supplies the working directory, +reads resolved files, records dependencies, supplies expanded tokens, and +bridges diagnostics. +`texrra-core::layout_primitive` owns the primitive set, operand scan order, +and typed effect contract for `\\par`, `\\newline`, `\\pagebreak`, +`\\penalty`, `\\kern`, `\\hskip`, and `\\vskip`; `engine::layout_primitive` +is a compatibility re-export. The Texlang adapter still provides the token +cursor and concrete integer, dimension, and glue scanners, then writes +source-located events from the core effects. +`NativeCommandTable` selects their Rust semantics, along with `\\advance`, +`\\multiply`, `\\divide`, `\\global`, `\\long`, `\\outer`, and `\\relax`. The +Texlang adapter still supplies the token cursor and converts typed layout +effects into source-located output events; other execution commands still use +the VM command map. +`engine::variable` also owns parsing and applying arithmetic-variable assignments +through a VM hook. Texlang still provides their descriptors and dynamic index +resolution; non-arithmetic variable assignments use its compatibility path. +`CompilerSession::interpret_document` now makes the frontend stages +explicit: `frontend::preprocess` returns `PreprocessedSource`, +`frontend::expand_tex` returns `ExpandedTexSource`, and +`frontend::lower_math` returns `LoweredDocumentSource`; only then does +`parser::parse_document` return a `ParsedDocument` with unresolved reference +nodes. `texrra-core::math_mode::validate_math_delimiters` validates inline +and display scope transitions, matching closes, and math-only command context; +this core state validates math scopes only; outer vertical and horizontal mode +transitions are still handled by the application document builder. +Math spacing in expanded items and the document IR uses the engine-owned +`MathMuGlue` value; only assignable VM variables retain Texlang's `MuGlue`, +which is converted when the expanded token snapshot is recorded. The math +layout and document IR modules no longer depend directly on Texlang types. +`texrra-core::glue::TeXGlue` owns glue width, stretch/shrink amounts, and +infinity orders; `engine::glue` is a compatibility re-export. Horizontal +`\\hskip` values preserve these fields through the expanded stream, document +runs, and inline math lists. Vertical `\\vskip` carries the same +glue fields into the Rust page-break node list. Positioned frames currently +apply its natural width; page-level glue setting is not yet implemented. +`texrra-core::integer` owns TeX integer scanning, including signs, octal +and hexadecimal forms, character constants, internal integer values, and +source-token retention. The adapter only supplies the token cursor and typed +variable lookup. Dimension expressions, register indices, and `\\penalty` use +that shared scanner. `engine::dimension` now scans explicit TeX dimensions and evaluates the +e-TeX `\\dimexpr` operators (`+`, `-`, `*`, `/`) with nested parentheses and +`\\relax` termination using scaled-point arithmetic. `\\glueexpr` uses the same +operators over width, stretch, shrink, and their TeX infinity orders. The Rust +scanner now parses decimal, octal, hexadecimal, and character-constant integers +for register indices and expression factors, and reads native typed register +variables directly from engine state. Active `\\count`, +`\\dimen`, `\\skip`, `\\muskip`, and `\\toks` values now live in sparse +Rust-owned tables in `engine::registers`; the corresponding `*def` aliases +point into those tables. Each table records local assignments for group +restore and clears those saves for global assignments. The old Texlang register +components have been removed from `CompilerState`. Texlang's `i32`, `Scaled`, +`Glue`, and `MuGlue` parsers now call Rust scanner hooks first, so assignments, +arithmetic operands, and explicit dimension/glue primitives share the same +engine scanners. The Rust state owns `\\mag` with TeX's 1000 default and +group-scoped assignment behavior; `true` dimensions use that value. `em` and +`ex` still use Texlang's 12 pt fallback until selected-font metrics are wired +into the scanner. The PDF backend does not yet apply `\\mag` as a whole-page +output scale, so this does not claim full XeTeX `\\mag` behavior. Unsupported +internal-value forms return to Texlang's parser. +The dimension and glue scanners serve `\\kern`, `\\hskip`, `\\vskip`, and math +`\\above` thickness. +`texrra-core::references::resolve` consumes the parsed type and returns the +resolved `DocumentModel`, so PDF and HTML receive the same post-semantic model. +PDF and HTML both use this same path. Preprocessing and expansion adaptation +are in `src/rust_typeset/frontend.rs`; math lowering and math syntax parsing are +in `crates/texrra-core/src/math_lowering.rs` and +`crates/texrra-core/src/math_parser.rs`. Semantic parsing and the document IR +are in `crates/texrra-core/src/document_parser.rs` and +`crates/texrra-core/src/document.rs` (`src/rust_typeset/parser.rs` and +`src/rust_typeset/document.rs` are compatibility re-exports). The PDF backend entry point is in +`src/rust_typeset/pdf.rs`. Rust page-break planning and positioned-frame +construction now live in `src/rust_typeset/pdf/layout.rs`; the PDF module owns +document/font setup and paints those frames through `genpdf`. The +`layout_document` returns positioned page frames, an optional cache snapshot, +and any page-break plan; the PDF backend consumes the frames and commits a +snapshot only after PDF rendering succeeds. If it cannot yet produce +Rust-owned frames, it preserves any valid page-break plan for the existing +`genpdf` flow. Documents made from title metadata, paragraphs, headings, and +math now use Rust-owned page frames. `itemize` and `enumerate` lists are stored +as nested item trees and use recursive Rust layout, hanging indents, the four +article list label styles, and 11pt article-style list spacing. Every list line +carries a stable page-break anchor and participates in the page-layout cache +key. Title metadata is currently laid out without page-layout snapshot reuse so +edits cannot reuse stale title positions. Custom `\\item` labels are not yet +represented in the document IR. Text lines, inline-math lines, and measured +two-dimensional math boxes are passed to the PDF painter at explicit vertical +offsets. Block display math uses one shared Rust layout routine for the cached +`MathBox`, formula position, row shifts, and equation-tag baselines; the PDF +painter and SVG renderer then consume those same calculated positions. The +browser editor previews these positioned page frames. `/preview` lays the +document out into the same `PositionedPage` items the PDF painter consumes, then +serializes each page to inline SVG in `src/rust_typeset/pdf/preview.rs`. The +browser page stack keeps one element per page and replaces only pages whose +content hash changed, so unchanged pages keep their DOM, scroll position, and +paint. Font faces and font metrics stay cached in `CompilerSession`, and font +files are served once from `/fonts/*` with immutable cache headers. `/compile` +paints the same frames to PDF, and `/texrra` remains the parser-model HTML +debug view. Simple +tables use Rust page frames too: cell lines, column alignment, +row heights, and horizontal rules are positioned by the page tree. Tables may +span pages with stable break anchors between rows, while each row stays intact. +A row taller than the available page still falls back to `genpdf`. Explicit +page breaks become forced page penalties in the Rust page +builder. Static images and their captions are measured and positioned as one +Rust page item; image-content fingerprints invalidate cached page breaks when +the file changes. Float queues and deferred `figure` placement are not yet +implemented. Simple resolved bibliography blocks now use Rust-owned frames +with a `References` heading and numbered, wrapped entries; full BibTeX style +semantics and custom `\\bibitem` labels are not represented yet. Unsupported +blocks still use the existing page-flow fallback for the whole document. +The document IR stores table column alignment in an engine-owned enum, and the +parser no longer imports `genpdf`; conversion to backend alignment happens only +inside the PDF layout path. +Shared TeX glyph metrics live in +`src/rust_typeset/box_font.rs` and +are used by both paragraph and math layout. +The preprocessing stage now preserves the input text and records source +locations; it does not rewrite package or command definitions. The TeX VM output +boundary records an ordered `ExpandedItem` stream: +expanded tokens retain their TeX category, control-sequence name, and source +location, while execution events retain their typed payload and source +location. A small local extension to `texlang` exposes executed brace-group +boundaries, which the stream records as typed events; math parsing uses the +stream for script categories and the events for nested groups. The document +parser now consumes the ordered token/event stream directly. The VM's serialized +text view remains inside expansion for checkpoint slicing and source-map lookup. +Math-shift normalization and math lowering operate directly on typed tokens and +events. The resulting `ExpandedTokenStream` retains typed items, events, and +source segments but no text buffer. Semantic math parsing reconstructs leaf +content from token categories, while paragraph text is likewise rebuilt from +token categories with control-sequence spelling handled explicitly. Source +segments retain character-boundary offsets for source-column mapping instead of +rescanning serialized output. +Math parsing returns source-located diagnostics for repeated superscripts or +subscripts instead of silently replacing the first script, and reports a +missing script argument instead of rendering `^` or `_` as an ordinary atom. +Only successfully parsed math trees enter the math parse cache. +Dollar math delimiters are recognized from math-shift tokens with an explicit +text/inline/display mode state: `$$` opens display math in text mode, `$` closes +inline math one token at a time, and display math requires a paired closer. +Unclosed math shifts produce source-located errors instead of plain text. +Macro-argument braces consumed while the VM reads an argument are not separate +execution events. This is a structural migration step, not a claim of XeTeX compatibility: +the VM is still Texlang rather than a XeTeX rewrite, and its box/glue lists and +page tree cover only a limited document subset. The frontend still scans source +to decide whether incremental snapshots are safe, but that scan does not alter +TeX execution. +The compatibility macros `\\makeatletter` and `\\makeatother` now change the VM's +catcode for `@`; preprocessing preserves control-sequence spelling instead of +rewriting `@` to `X`. +The engine-owned catcode table now follows local and global assignment scope: +group exit restores local changes, while global changes survive all open +groups. The mouth and Texlang's `\\catcode` variable adapter now read and mutate +the same table, removing the duplicated catcode array and post-assignment sync +step. `texrra-core::assignment_scope::AssignmentScope` owns the scoped +`\\globaldefs` value and applies its global/local override after the Rust +prefix scanner consumes `\\global`; `\\globaldefs` itself follows the same +group save rules. `engine::prefix` scans and validates `\\global`, `\\long`, +and `\\outer` using command tags as registry metadata. `\\gdef` and `\\xdef` +also honor a negative `\\globaldefs` instead of forcing global scope. Brace +groups, the `\\begingroup` / `\\endgroup` primitives, and non-document +environments share the engine save stack. `\\bgroup` / +`\\egroup` expand through the same group primitives. The project-owned mouth +supplies live tokenization; the VM remains Texlang-based for the execution +loop, primitive dispatch, and replacement-token transport. The Rust primitive +map now routes `\\advance`, `\\multiply`, and `\\divide` through +`engine::arithmetic`, which owns command dispatch and arithmetic, overflow, and +division-error behavior. Texlang parser hooks route integer, dimension, ordinary +glue, and math-glue values through the Rust scanners for assignments and +arithmetic operands. Arithmetic-variable assignment now uses the Rust-owned +assignment path, while descriptors and dynamic indices still pass through the +Texlang adapter. +`\newcommand`, `\renewcommand`, `\providecommand`, `\def`, and `\gdef` remain +in the input stream, and the preprocessor copies their replacement bodies +without inspecting them. The Rust VM stores definitions in its scoped macro +table and expands positional arguments itself. Rust macro definitions now +retain `\\long` and `\\outer`: non-long argument scans reject `\\par`, while +outer macro calls are rejected in Rust macro-argument scans, shared +braced/optional argument scans, generic Rust token-list scans, and expanded +definitions. The generic token-list adapter checks captured, unexpanded tokens +so token-register arguments keep their existing read behavior. This does not +yet cover every TeX scanner context. Unstarred +`\\newcommand` is long and its starred form is non-long. LaTeX command definitions +support one optional first parameter and up to eight following required +parameters when a default is present, or up to nine required parameters without +one. TeX `\def` / `\gdef` support ordered numbered parameters, literal prefixes +and delimiters, and replacement references; `\let` preserves an engine-owned +macro's current meaning using the macro table as its source of truth. `\edef` +and `\xdef` store Rust-owned definitions and replacement token values. Macro +arguments and replacement bodies retain engine trace IDs, which the adapter +maps to Texlang trace keys for source diagnostics; conversion occurs only at +the unexpanded-input and expansion-stack boundaries. This does not claim full +LaTeX command-definition compatibility. +Paragraph breaks, page +breaks, `\\maketitle`, title/author/date bodies, section headings, `\\begin` / +`\\end` environment boundaries, labels, references, citations, bibliography +item keys, and geometry settings travel as typed frontend events with their +arguments already consumed by the TeX expander. The metadata bodies use paired +typed events around ordinary expanded tokens, so they no longer need marker +strings. `\\begin` and `\\end` update a serialized, engine-owned environment +stack; `\\end` rejects an unmatched or out-of-order close during execution. +Non-document environments also open and close a TeX assignment group so local +definitions and register changes restore at `\\end`; the `document` environment +stays at top-level scope. +`array`, `tabular`, `alignedat`, and `alignat` preambles are consumed as TeX +token arguments and carried as typed environment events. +`\\bibitem` now reads its optional label and citation key in the VM and emits a +typed bibliography-item event; the optional label is still ignored by layout. +`\\bibliography` also reads its file list in the VM, loads and records `.bib` +dependencies there, and feeds formatted entries back through the VM token +stream. Generated bibliography tokens retain the originating command's source +location. The BibTeX reader and formatter are still a limited implementation. +Raw alignment-tab tokens become typed table or math-cell events according to +the active environment; a misplaced `&` reports a TeX-style error instead of +being rewritten into a literal ampersand. Bold, italic, and monospaced text switches, list items, +table cells, rules, and escaped ampersands now travel as typed events with +source locations instead of private string markers. Image commands now carry +their parsed options and path as one typed event, preserving the command's +source location and removing the marker pair used to hand image data to the +document parser. `\\includegraphics` now reads its star, optional key-value +options, and braced path from the VM token stream; common width and height +register names are normalized there instead of by scanning raw source text. +Captions use paired events, so the document parser can collect +their runs while still interpreting text styles, references, and inline math. +Escaped braces, ampersands, and `\\newline` also travel as typed events; their +literal characters and line-break behavior no longer pass through private +marker text. +Row breaks and math alignment cell boundaries also travel as typed events. +The `\\frac`, `\\dfrac`, `\\tfrac`, `\\binom`, `\\dbinom`, and `\\tbinom` +commands emit paired typed events for fraction start, argument boundary, and +end; the math parser consumes these into nested `MathExpr::Fraction` nodes. +Plain TeX's infix `\\over`, `\\atop`, `\\choose`, and `\\above ` are also +typed math events: they split the current math group into numerator and +denominator, with `\\over` drawing the font's default rule, `\\atop` omitting +it, `\\choose` adding stretched parentheses, and `\\above` using its explicit +rule thickness. A zero-thickness `\\above` uses the no-rule stack clearance. +The delimiter forms `\\overwithdelims`, `\\atopwithdelims`, and +`\\abovewithdelims` scan two delimiters (and then the dimension for the last +form), retaining their glyph and sizing settings on the fraction event. The +math parser wraps the shared fraction node in the same scalable delimiter box +used by `\\left` and `\\right`. +They lower to the same fraction node used by the braced commands, so PDF and +HTML preview keep the same two-dimensional layout. A second infix fraction +separator in the same math group reports TeX's ambiguity error at the second +separator. The custom rule and no-rule spacing follow XeTeX's +[fraction construction](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L24875-L24904). +The four TeX math-style commands are typed state changes inside the math tree. +They affect following atoms, spacing, fractions, operators, and scripts in the +current group, and nested groups restore their inherited style. The PDF and SVG +math-box layout consumes the same style-aware tree. +Text-mode math groups such as `\text{...}` use an upright text face at the +active math size rather than inheriting the surrounding math italic face. +Nested bold, italic, and monospaced text-style events remain separate styled +runs in the math tree. PDF and SVG preview use the selected family and preserve +formatting such as `\textbf{...}` and `\texttt{...}` inside `\text{...}`. +In math mode, `\phantom`, `\hphantom`, and `\vphantom` become box nodes in the +same tree. PDF and SVG layout measure the child once, then retain its full, +horizontal-only, or vertical-only extent while emitting no paint items. +The primitive `\\mathchoice` retains its display, text, script, and scriptscript +branches as scoped math trees. The shared PDF/SVG layout selects the branch from +the active TeX math style, including inside scripts and nested choices. Math-box +and inline-paragraph cache keys recursively retain only selected alternatives, +using the style transitions for fractions, scripts, roots, accents, and alignment +cells. Editing an unselected branch therefore preserves both the selected box +and the paragraph line-break result. +The `\\sqrt` command and its optional degree emit typed root-boundary events; +the math parser consumes them into nested `MathExpr::Root` nodes. `\\left`, +`\\middle`, and `\\right` emit typed delimiter events; paired fences become a +2D node whose delimiters share one content-based target height. Math font +switches, `\\operatorname` and common +operator macros, `\\overline`, `\\underline`, `\\vec`, and directional arrow +accents above and below the nucleus now use typed math events. `\\xleftarrow`, +`\\xrightarrow`, and `\\xleftrightarrow` currently accept one label. They enter +through `\\Umathaccent` as relation-class nodes, so the shared math layout can +use family-2 OpenType MATH glyph variants and horizontal assemblies. Optional +lower labels for these commands are not implemented yet. The math parser +consumes their event ranges into styled atoms and accent nodes. +The primitive math alphabet `\\mathtt` changes ordinary math leaves to the +same monospaced family used by PDF text and `\\texttt`, while keeping fractions, +scripts, and other two-dimensional structures intact. +The math alphabets `\\mathit`, `\\mathbf`, `\\boldsymbol`, `\\mathsf`, +`\\mathcal`, `\\mathbb`, and `\\mathfrak` map Latin and Greek letters and +supported digits to Unicode mathematical alphanumeric glyphs when the active +math font contains them. Missing glyphs retain the source character and use a +matching upright, bold, or italic text face; script kern and italic-correction +lookups use the mapped glyph when it is available. The Unicode mapping follows +the [Mathematical Alphanumeric Symbols chart](https://www.unicode.org/charts/PDF/U1D400.pdf). +`\\sqrt`, `\\left`, `\\middle`, and `\\right` are handled by Rust VM primitives; the frontend no longer scans +their arguments from raw source text. Root arguments are captured as TeX tokens +and returned to the VM expansion stack, preserving nested macros and group +execution while the typed root events delimit the resulting math tree. +The `\\mathord`, `\\mathop`, `\\mathbin`, `\\mathrel`, `\\mathopen`, +`\\mathclose`, `\\mathpunct`, and `\\mathinner` commands preserve their +explicit noad class as a typed wrapper around the math nucleus. Class wrappers +participate in TeX's math spacing table and operator limit placement without +flattening the nucleus into text. +The `\\stackrel` compatibility macro builds an operator with stacked limits +and restores the relation class around the resulting noad. `\\substack` lowers +to `smallmatrix`, so row breaks become a centered two-dimensional stack whose +entries use script style. +Ordinary math tokens capture their current engine `\\mathcode` in the source-spanned +VM token stream. The math parser carries its class, family, and slot into the math +IR, so assignments affect later tokens and respect the engine's grouping. The +`\\fam` integer parameter is also captured with each token; for class-7 math +codes, a current family from 0 to 15 overrides the family's math-code bits, and +the default `-1` leaves those bits in effect. Family 1 renders ordinary +variables in the italic face; family 0 stays upright, and printable ASCII +slots can remap the rendered glyph. Explicit roman math groups lower family 1 +to the upright face while nested explicit font groups keep their own selection. +The VM now exposes `\\font`, `\\textfont`, `\\scriptfont`, and +`\\scriptscriptfont`: `\\font\\mathface=fonts/math.ttf` loads a local font +file, and the three family registers can assign that font to family 0–255. +Ordinary math atoms then use the assigned outline at the active math style size; +font-register state is captured with each expanded token so local assignments +survive into the math tree, and the same rasterized glyph is used by PDF and +SVG. This first slice does not yet shape regular text through `\\font` or use +math-active (`"8000`) expansion. Unicode characters with an unset zero code use the +existing character fallback. +The VM's `\\mathchar` primitive and `\\mathchardef` commands now emit typed +math-character events containing the 15-bit math code and current `\\fam`. +These become ordinary math atoms with the specified class, family, and slot; +using a math character outside math mode produces a source-located diagnostic. +The `\\mathchardef` primitive installs a scoped math-character command, and +`\\Umathchardef` installs a native scoped Unicode math-character command. Both +definitions honor local and global assignment scope; Unicode class-7 commands +read the current `\\fam` when they are used. +The `\\Umathchar` primitive also accepts XeTeX's class, family, and Unicode +character arguments and sends the resulting atom through the same math layout +path. Class 7 uses the current `\\fam` when it is in the supported range and +otherwise keeps the explicitly supplied family, matching XeTeX's `set_math_char` +behavior. Assigned font registers select the corresponding face for ordinary +glyphs; without an assignment, atoms keep the configured math font and existing +upright/italic fallback. Mathematical alphanumeric codepoints in +U+1D400–U+1D7FF prefer the configured MATH font when no family font overrides +them, preserving encoded italic and bold glyph forms when the face contains +them. +The packed `\\Umathcharnum` and `\\Umathcharnumdef` forms decode the same +class/family/Unicode-slot bit fields used by `\\Umathcode`, then share the +regular Unicode math-character event and layout path. +The `\\Udelimiter` primitive accepts Unicode opening and closing delimiter +types (4 and 5), family, and scalar glyph slot, then lowers to the same scalable +delimiter layout used by the PDF and SVG paths. Its family now selects the +glyph's MATH variant or assembly at the active style size, with the configured +MATH font as fallback when the family has no registered face. The initial size +target follows the active math style. Classic `\\left`, `\\middle`, and `\\right` +read the 24-bit `\\delcode` fields for small and large glyph families and slots. +Their family register snapshots select the matching face at text, script, or +scriptscript size, and the shared layout tries the small-family glyph before the +large-family glyph. Common ASCII delimiters default to family 0; users can assign +other delimiter codes with normal local and global TeX scoping. +Display-style single-glyph operators now use the assigned family font's +vertical MATH variants and `DisplayOperatorMinHeight` when available; operators +without an assigned family continue to use the configured MATH font. +Delimiter centering and display-operator alignment now read `AxisHeight` from +the current family-2 math font at the active style size when it supplies OpenType +MATH constants, falling back to the configured math metrics font otherwise. +Glyph-based standard accents (`\\hat`, `\\tilde`, `\\widehat`, `\\widetilde`, +`\\overbrace`, and `\\underbrace`) capture the current `\\fam` and use that +family's font and MATH construction at the active style size. Rule accents +(`\\overline` and `\\underline`) remain geometric rules and use the nucleus +font's MATH spacing and rule constants when available. +The `\\Uradical` primitive accepts a family and scalar glyph slot followed by +the radicand. It enters the same typed root node and shared PDF/SVG radical +layout as `\\sqrt`. The requested family now selects the radical glyph's MATH +variant or assembly at the active math style size. When that family has no +registered face, lookup falls back to the configured MATH font. Radical spacing +and degree placement use the selected face's MATH constants when present, then +fall back to the configured MATH metrics face. +The `\\Umathaccent` primitive accepts XeTeX's optional `fixed` and `bottom` +keywords, math class, family, and scalar glyph slot, then captures the following +nucleus as a typed accent node. Stretchable accents use horizontal MATH variants +or assemblies from the requested family, and fixed accents paint its requested +glyph. Accent placement reads `AccentBaseHeight` and the base glyph's top-accent +attachment from the nucleus face when available; the requested accent face +supplies the accent glyph and its top-accent attachment. Missing nucleus MATH +data falls back to the configured metrics face. When the family has no +registered face, glyph lookup falls back to the configured MATH font. Bottom +accents use the under-accent placement path. +`\\Umathcode` assignments now store the Unicode input character's math class, +family, and glyph slot in the engine-owned scoped variable table. Later occurrences consume that +mapping from the expanded token stream, and the math parse cache includes it in +its key. Class 7 uses the current `\\fam` when it is in the supported range; +otherwise it keeps the assigned family, matching the existing legacy-mathcode +fallback. Assigned font registers select ordinary atom glyphs; the configured +MATH font supplies structural glyph variants where no family font is assigned. +Math nodes capture family-2 font selections at the point where fractions and +delimiters are introduced. When the selected face has MATH data, its style +scales, fraction constants, and axis height drive those layouts; missing MATH +data falls back to the configured metrics face. +Explicit math spaces (`\\,`, `\\:`, `\\;`, `\\!`, `\\quad`, and `\\qquad`) +now travel as source-located glue events. `\\left` and `\\right` lower to typed +delimiter events whether written directly or reached through the prelude +macros. Script argument scanning now recognizes source-spanned math containers, +so an unbraced `\\frac`, `\\sqrt`, delimiter group, or styled atom remains one +script node. The document parser now consumes the same token/event stream. +Cross-reference and citation events remain typed unresolved inline runs through +document parsing; `references::resolve` handles them as a separate semantic +pass after all labels and citations have been collected. +The frontend now pairs math delimiters and display-math environment boundaries, +parses typed fraction, root, and delimiter events into `MathExpr`, and emits a +single typed inline or display math event. The document +parser inserts that expression directly; math bodies no longer pass through its +string accumulator, and there is no document-parser fallback that rewrites a +fraction to slash-separated text. Math nodes retain source locations down to atoms, fractions, roots, +delimiters, and scripts. The math parse cache keys source-origin segment +shape rather than absolute line and column numbers, then rebases cached node +locations to the current source map. The math-box cache removes source locations +from its keys, so moving a formula does not discard reusable geometry. +Within an expression, the parser reads ordinary characters and text/operator +leaves from expanded token values; its cache identity uses token and event data +rather than the serialized math string. Math environment names and preambles +arrive as typed VM events. Math lowering uses serialized byte ranges to copy +surrounding document content; source mapping still uses the serialized view to +translate VM offsets into original source columns. +Math lowering copies expanded items in item order instead of splitting them by +byte position. Space tokens and events are zero-width items, so they share their +byte position with the following token; position-based copying placed an event +between the space that preceded it and the token that followed, which moved the +space before `\ref`, `\cite`, `\textbf`, and inline math to the end of the +reference text. `ExpandedTokenStream::copy_items` now copies an item slice +together with its source segments and rebases both, and both lowering passes +track each event's item index so tokens that precede an event stay before it. +The private tag-string protocol and cross-reference string sentinels have been +removed. Reference and citation values remain typed inside their runs until the +dedicated reference-resolution pass runs after document parsing. +Preprocessing and macro expansion carry file, line, and column +locations through generated text; parsed blocks retain source anchors, which +the HTML preview exposes as `data-tex-source-*` attributes. Most non-math +commands are not yet represented as a source-spanned syntax tree. +Display math is a separate layout module at +`src/rust_typeset/math_layout.rs`. The document parser consumes token/event +items directly, but the document model is not yet a source-spanned syntax tree. +Each request checks the source identity, loaded file contents, and available +`.sty` filenames. The session retains three complete compilation snapshots in +least-recently-used order. An exact source/configuration hit with unchanged +dependencies skips preprocessing, TeX expansion, math lowering, and document +parsing; recent undo/redo versions can therefore reuse the complete semantic +model. A changed dependency invalidates that snapshot. Reads made by +The Rust `\input` adapter records each resolved file as a source dependency; +diagnostics in imported files retain their own source locations. Style, +bibliography, and input changes invalidate the cached result. Commands with untracked I/O or +dynamic token behavior bypass this cache. For cacheable documents with a +literal `\begin{document}` on a line whose preceding characters are +whitespace, the session retains a serialized Texlang VM checkpoint immediately +before that command. It preserves the preamble's macro definitions, catcodes, +registers, groups, and other VM state. The body is divided at blank-line +paragraph boundaries; after a chunk runs, a checkpoint is kept only when TeX +groups are closed and the active environment is empty or `document`. Up to +eight checkpoints are sampled across the body within a bounded memory budget. +On a later edit, the compiler finds the latest checkpoint whose preceding body +text is byte-for-byte unchanged, restores the VM and expanded output prefix, +then expands the remaining body. Runtime and preprocessing dependencies are +checked before reuse. This skips expansion of an unchanged body prefix, while +preprocessing, math lowering, semantic parsing, and PDF generation still visit +the full document. If a chunk ends while TeX is waiting for more input, the +compiler falls back to the unsplit expansion path. Documents that cannot use +the preamble checkpoint also use that full path. During each body pass, +math parse-cache identity uses expression text, expanded token values and +categories, math-code +values, source-origin segment shape, frontend events, and math environment. +Token and event positions are relative to the expression; absolute source line +and column numbers do not prevent reuse. +On a cache hit, the compiler rebases cached math-node locations to the current +source segments and events; ambiguous mappings decline reuse. Unchanged +equations can therefore retain parsed trees when edits above them move their +source locations. Paragraph line boxes and math subtrees can reuse layout +results too. Plain top-level paragraphs reuse their normalized run sequence by +exact expanded text. Top-level paragraphs with inline math, references, or +citations also reuse their run sequence when the full expanded token/event +sequence and source locations match; references stay unresolved in the cache +and are resolved against the current document after parsing. Styled paragraphs +and content inside lists, tables, figures, or bibliography continue through the +full parser. Every compile emits a fresh PDF. +The live HTML and PDF endpoints share the same `CompilerSession`, so an +unchanged expanded document reuses its parsed model across either endpoint. +The editor session now reuses cached Knuth–Plass line breaks for unchanged +plain-text paragraphs. The line breaker receives explicit glyph, glue, kern, +and penalty nodes, using the same Latin, CJK, and monospaced font faces as the +PDF renderer, including bold and italic variants. It includes pair kerning in +line-width calculations, offers breakpoints between CJK characters, and blocks +breaks after opening or before common closing punctuation and small kana. Cache +keys include the complete styled paragraph, line width, participating +font-content fingerprints, and size; a changed layout input produces a fresh +result. The cache stores packed line boxes with their glyphs and adjusted glue +widths. A Rust `TextLine` element paints them at explicit baselines, so +`genpdf` does not choose their line breaks or word-space positions again. It +provides the PDF drawing primitives; documents with blocks that do not yet fit +the Rust page model still use its page-flow fallback. +For documents made from paragraphs (including inline math), headings, lists, +simple tables, and display-math blocks, a Rust page builder creates a vertical +list of line boxes, table rows, spacing glue, and break penalties. It chooses +page-break anchors with TeX-style badness and penalty costs, then the PDF path +paints the positioned page frames directly. +This is a first port of the `vert_break` behavior in XeTeX's `xetex.web`, +limited to fixed-height boxes and the current paragraph/heading skips. Text and +math line boxes carry separate height and depth; page planning applies the +11pt article `\topskip` and 5.5pt `\maxdepth`, and measured multi-line +paragraphs add fixed glue to keep successive baselines at the configured +size-specific distance. The page builder keeps the current depth separate from +the accumulated page height, caps it at `\maxdepth`, and uses the same line +metrics and leading as positioned PDF frames. It also discards leading glue and +penalties before the first box on a page. If baseline glue would become +negative, line layout uses the article class's 1pt `\lineskip` fallback. +Vertical glue records normal and infinite stretch orders plus shrink. Page-break +costs use these amounts, including the 11pt article list `\topsep` and +`\itemsep` values. PDF frame placement still uses natural glue widths, so page +level stretch and shrink are not yet applied to the rendered page. +Display math uses the 11pt article normal skips (11pt plus 3pt minus 6pt) and +short skips (above: 0pt plus 3pt; below: 6.5pt plus 3.5pt minus 3pt). The +engine measures the preceding paragraph's final line and chooses the short skips when +the centered formula starts to the right of that line's natural end plus two +em. Paragraph glue that changes visible content forces the normal skips, as in +TeX's `\predisplaysize` calculation. The current model does not yet include +equation numbers, paragraph shapes, or display indentation. The class values +follow the [standard document class definitions](https://www.latex-project.org/help/documentation/classes.pdf), +and the short-skip decision follows XeTeX's +[display-math algorithm](https://tug.ctan.org/info/knuth-pdf/xetex/xetex.pdf). +Page-start anchors and each decision's look-ahead range are retained across +edits; planning resumes from the earliest page whose decision inspected changed +content. Font or page-geometry changes and non-tail block insertions/deletions +trigger a full page-break pass. +Simple resolved bibliography blocks also use Rust-owned frames: the heading +and numbered entries have stable line anchors, and bibliography keys and +resolved runs are part of the page-layout cache key. Full bibliography style +semantics and custom `\\bibitem` labels are not represented yet. A table row +taller than the available page still uses the `genpdf` fallback. +Explicit page breaks use forced penalties when the Rust page model can handle +the rest of the document. The Rust page builder does not yet model float +queues, insertion nodes, output routines, or page-level glue distribution. +Baseline glue is currently fixed and the supported size table is only a small +article-style subset. +Inline-math paragraphs also reuse their measured, positioned line boxes across +compiles. This bounded session cache keys source-independent math trees, styled +text runs, line width, font-content fingerprints, and math metrics, so moving +an unchanged formula in the source does not discard its PDF paragraph layout. +Inline formulas in the live preview are serialized from the measured math boxes, +so they share paragraph line breaks and glyph positions with the PDF. The +separate `/texrra` debug view still serializes inline formulas without the +positioned page frames. +Display and inline math now use positioned `MathBox` nodes. PDF paints those +nodes through its font cache; the HTML endpoint serializes the same layout +algorithm and font metrics as SVG, embedding the matching Liberation Serif +faces and, when used, Liberation Mono. SVG text spans carry the advance width +computed by the shared font cache and preserve whitespace, so browser text +spacing does not silently change the measured math box. The compiler session +retains one bounded FIFO cache of math boxes shared +by both renderers, keyed by each expression node, math style, font and +MATH-metrics fingerprints, and rendering style. PDF and HTML therefore paint +or serialize the same positioned box tree. Parent boxes share cached child +boxes, so editing one part of a fraction or script can reuse unchanged +subtrees. Changes to any layout input produce a fresh box, while unchanged +boxes are reused across both endpoints. +`CompilerSession` also retains the active `MathFontMetrics` across PDF and HTML +render calls. Its content fingerprint covers the selected MATH metrics face, +the four Liberation Serif faces, and each document-selected math font, so a +font-file change reloads the snapshot. Cloned metrics share the per-glyph MATH +data cache. +Inline expressions remain `MathExpr` values inside paragraph runs, while +display equations enter the same line-breaking stage without prose. Their +top-level sequence atoms become measured horizontal boxes. Word spaces are +stretchable glue; math relations, binary operators, and punctuation add +penalized breakpoints. A leading math-class spacer is dropped when a break +begins a new line. Fractions, scripts, radicals, and delimiters stay as +indivisible two-dimensional boxes. This is a first useful slice, not full TeX +math breaking: nested sequences remain indivisible, operator-specific +penalties and math font shaping are incomplete. Math alignment tabs and typed +row-break events form a two-dimensional cell grid. Matrix environments add their paired +delimiters; `cases` adds a left brace; `aligned` aligns right/left cell pairs +and inserts the inter-pair gap, while `alignedat` leaves pair spacing to the +source. `gathered` centers each row, and `array` reads simple `l`, `c`, and `r` +columns, single or repeated vertical rules (`|`), and repeated column patterns +such as `*{3}{c|}`. The source preamble is captured before TeX grouping removes +its braces. Array rules render as vector rectangles in SVG and 600 dpi RGB +images in PDF, using the default 5 pt column padding, 0.4 pt rule width, and +2 pt separation between repeated rules. This does not implement complete +`array` or `amsmath` alignment semantics. The editor displays this layout as +live SVG pages, and the PDF export paints the same frames. The separate +experimental HTML endpoint still serializes complete math expressions through +browser flow layout and does not share the positioned page frames. The box tree remains local +to math; deferred float placement is not yet represented by the positioned page +model. Paragraphs with or without inline math, headings, standalone display +math, nested lists, simple tables, static images with captions, resolved +bibliographies, and explicit page breaks use Rust-owned positioned page frames, +including title metadata. Unsupported blocks still route the whole document +through the `genpdf` page-flow fallback. + +Alignment nodes also retain their environment's cell math style. `matrix`, +`array`, and `cases` lay out cells in text style; `smallmatrix` uses script +style; and `aligned`, `alignedat`, `gathered`, and display alignment +environments use display style. This controls nested fraction sizing, operator +variants, and math-class spacing inside each cell instead of inheriting the +outer formula's style unconditionally. + +Alignment nodes also retain a baseline policy. Top-level display alignments +keep the first row baseline for row tags. Nested `aligned`, `split`, `gathered`, +matrix, array, and cases boxes center their vertical extent on the math axis, so +an enclosing `equation` retains the inner grid's geometry. The baseline follows +XeTeX's `make_vcenter` rule: math axis height plus half the box's total height +([XeTeX source](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L16363-L16372)). The axis uses the family-2 font's OpenType +MATH constant when available, with the configured metric as fallback. + +## Rust core rewrite target + +The current pipeline is a Rust implementation of a limited LaTeX subset, not a +Rust rewrite of the XeTeX core. It reconstructs a reduced document model from +the TeX VM's token/event stream and delegates PDF drawing, plus non-text-only +page flow, to `genpdf`. The full XeTeX behavior is not present. + +The rewrite target keeps a clear boundary between four Rust-owned phases: + +1. A source-aware TeX frontend owns tokenization, category codes, macro + expansion, and diagnostics. Commands and environments must remain structured + values rather than being encoded as marker strings. +2. A typesetting engine turns the expanded input into semantic nodes and then + TeX-like horizontal and vertical lists: glyph runs, glue, penalties, math + atoms, boxes, and insertions. +3. A page-layout engine performs shaping, line breaking, float placement, and + page breaking into one positioned page tree with baselines and source anchors. +4. PDF output and the live preview consume that same page tree, so both views + share glyph positions, line breaks, math geometry, and pagination. + +Incremental recompilation belongs at the phase boundaries: source edits dirty +the affected syntax and macro dependencies, changed paragraphs invalidate only +their line boxes, and page-level changes reflow from the earliest affected +page. The current paragraph FIFO cache is an isolated optimization and is not +yet this dependency model. + +The live preview adds one more reuse boundary: a preview response recomputes the +positioned frames, hashes each page's serialized SVG, and lets the browser +replace only changed pages. Reusing the frames themselves across requests, +rather than only their line boxes and page-break plan, is the next step toward +per-page incremental rendering. + +The target is a native Rust rewrite of XeTeX's engine core, not a wrapper +around XeLaTeX. The upstream XeTeX and TeX sources are implementation +references: port well-scoped algorithms and routines into Rust where their +file-level licenses allow it, then organize them around the phase boundaries +above instead of preserving the legacy WEB/C/C++ layout line by line. +XeLaTeX compatibility has two layers: XeTeX engine semantics (tokens, +expansion, registers, boxes, glue, math, page building, font shaping, and +output) and the LaTeX format/package layer built on that engine. The current +`texlang`, `boxworks`, `rusttype`, and `genpdf` dependencies provide Rust +scaffolding, but their use does not make this limited subset equivalent to +XeTeX. The rewrite must eventually own the semantic and layout contracts above; +each dependency should be removed or kept only as a replaceable implementation +detail. + +The rewrite proceeds in this order while keeping the editor runnable: + +1. Make the source-spanned token/event stream the only input to the compiler + front end. The stream is emitted by the TeX VM, and both document parsing + and math structural parsing now consume it. The serialized view remains + inside VM checkpoint and source-map support; remove those remaining + dependencies and move source preprocessing that interprets TeX syntax into + the VM or source/file world layer. +2. Extend the VM into the TeX execution engine: modes, grouping and assignment + semantics, registers, horizontal/vertical lists, glue, penalties, boxes, + insertions, and math noads. `texlang` remains a replaceable token-VM + foundation; it is not the engine itself. +3. Add Unicode font selection and shaping, TeX paragraph and page building, + and an engine-owned positioned page tree. PDF and the live preview must both + export that tree. Replace `genpdf` as the owner of page composition during + this phase. +4. Load the LaTeX format and package tree on top of the engine, then expand + compatibility against XeLaTeX reference output and diagnostics. This layer + is what makes the result XeLaTeX/LaTeX-compatible for real documents; the + TeX engine alone is not sufficient. + +The current dependency boundary and the source-by-source port order are tracked +in [the XeTeX Rust port map](xetex-rust-port-map.md). Treat the current engine +as a migration host until its TeX execution state, list model, typesetting +algorithms, and output tree have been replaced or verified against XeTeX. + +Font shaping is an engine requirement: XeTeX compatibility includes Unicode +shaping and OpenType/AAT/Graphite behavior where the chosen font stack supports +them. Incremental compilation is safe only at phase boundaries that account for +TeX's mutable state. Expansion reuse must include the macro definitions, +registers, category codes, and mode at a checkpoint; an edit invalidates forward +until those state values match again. Layout reuse keys the resulting node lists, +fonts, and dimensions, while page composition reflows from the first changed +page. + +Compatibility is tracked by observable behavior, not command names: each +slice records its TeX input, expected boxes/positions or PDF result, diagnostics, +font assumptions, and XeLaTeX reference behavior. A command is not marked +compatible merely because it parses or looks plausible. + +The first math slice keeps display formulas as structured expressions through +PDF layout. The math tree now keeps ordinary, operator, binary, relation, +opening, closing, punctuation, and inner atoms distinct. Layout applies TeX's +8-by-8 math spacing table, including binary-operator normalization and +style-dependent thin, medium, and thick spaces. Automatic inter-atom spacing +uses TeX's `thinmuskip`, `medmuskip`, and `thickmuskip` variables, initialized to +the LaTeX defaults (3mu, 4mu plus 2mu minus 4mu, and 5mu plus 5mu). Assignments +use the VM's normal group and global-assignment semantics. The expansion stream +records the effective values at each math token, so incremental layout, PDF, and +SVG preview share the same math spacing. Inline math line breaking can adjust +relation and binary spacing using the configured stretch and shrink. Indexed +`\muskip` registers and `\muskipdef` aliases now read and write the engine's +Rust-owned table. Their typed parser delegates to the Rust math-glue scanner +for direct assignments and arithmetic operands. It handles `\\muexpr`, `mu`, +`plus`, `minus`, and scaling expressions, then falls back to Texlang for forms +the engine scanner does not yet handle. +Explicit `\\,`, `\\:`, `\\;`, +`\\!`, `\\quad`, and `\\qquad` spacing is represented by source-located math +glue events. Math groups without local style changes keep their atoms in the +surrounding math list, so binary-operator normalization sees operands across +braces. Style-changing groups retain their local math style while inheriting +the neighboring atom classes needed to normalize operators at their edges. +Display fractions use stacked numerators and denominators; roots draw a rule over +their nuclei and use vertical MATH variants or assemblies for the radical sign. +Radical variants target the nucleus's full height plus the selected clearance and +rule thickness. The sign's baseline aligns with the bottom of the rule; when the +largest available sign exceeds the target, the rule and sign move up by half the +excess, increasing the actual nucleus clearance by the same amount. Legacy fonts +without MATH constants use XeTeX's fallback clearance: one rule thickness plus +one quarter x-height in display style, or one quarter rule thickness otherwise. +The `RadicalExtraAscender` MATH constant is not used by XeTeX's radical routine. +Math-list boxes now use the natural top and bottom extents of their laid-out +children; explicit math glue contributes horizontal width without adding a text +line's vertical strut. Text boxes inside math keep their own text metrics. This +prevents paragraph line height from inflating fractions and script boxes, in +line with XeTeX's natural packing of the converted math list +([XeTeX source](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/web2c/xetexdir/xetex.web)). +`\\sqrt[n]{x}` places the degree as a scaled child using the radical-degree +MATH constants; display limits on `\\sum`, `\\prod`, `\\lim`, +`\\max`, and `\\min` stack above and below. `\\limits`, `\\nolimits`, and +`\\displaylimits` now explicitly control operator-script placement and remain +typed, source-located events through math parsing. These rules follow the algorithms +used by XeTeX's math parameter tables. `\\frac`, `\\dfrac`, and `\\tfrac` retain +their automatic, display, and text fraction styles; child sizes, vertical gaps, +and rule thickness come from the active math style and OpenType MATH constants. +The compatibility prelude also lowers `\\overset{...}{...}` and +`\\underset{...}{...}` to operator limits, so their annotations use the same +two-dimensional script boxes. The current lowering treats the annotated base as +an operator; AMS `\\binrel@` class preservation remains to be ported. +`\\binom`, `\\dbinom`, and `\\tbinom` now reuse this stacked fraction layout +without drawing a rule, then measure and stretch parentheses around the box. +Displayed operator limits also reserve the OpenType `StackGapMin` outside the +upper and lower scripts, corresponding to XeTeX's `BigOpSpacing5`; fonts without +a MATH table use a 0.1 em fallback. Single-glyph operators also skew their upper +and lower limits in opposite directions using half the glyph's math italic +correction, following XeTeX's `make_op` layout. +`\\left...\\right` computes its target height from the largest distance to the +math axis and applies `\\delimiterfactor` and `\\delimitershortfall` before +selecting a MATH variant or assembly. Both are assignable TeX variables with +defaults 901 and 5pt; assignments follow TeX's local grouping and `\\global` +rules. The frontend captures the values at formula closure and applies that +snapshot to every delimiter in the formula, including fraction delimiters and +the parentheses around `\\choose` and `\\binom`, matching TeX's later math-list +conversion step. Variant selection compares OpenType MATH advance measurements, +not the rasterized ink bounds; if no variant reaches the target, the layout tries +an assembly and otherwise keeps the largest available variant. Assembly parts +are expanded in their MATH-table order; vertical assemblies are painted in the +reverse order used by XeTeX's vertical box. Part offsets and connector overlap +use each part's MATH `fullAdvance`; glyph ink bounds determine the painted image +bounds independently of the TeX box extent. This follows XeTeX's `var_delimiter` and +OpenType's bottom-to-top vertical part order +([XeTeX source](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/web2c/xetexdir/xetex.web), +[OpenType MATH specification](https://learn.microsoft.com/en-us/typography/opentype/spec/math)). +The plain-TeX manual delimiter family (big, Big, bigg, and Bigg, with +left, middle, and right atom-class forms) uses fixed 8.5, 11.5, 14.5, and +17.5 TeX-point virtual boxes to select the matching MATH variant or assembly. +Superscripts on character-like nuclei use the active glyph face's OpenType MATH +italic-correction value when that face provides one. Fonts without a correction +table fall back to the rendered glyph's right-side ink overhang, and non-italic +faces receive no outline-based correction. The selected face follows the same +regular, bold, italic, and bold-italic Liberation Serif files embedded in PDF +and preview output. Script placement now +uses OpenType MATH top/bottom limits, baseline-drop constraints, the minimum +superscript/subscript gap, and the combined-script superscript-bottom constraint +used by XeTeX. Fonts without those constants use EM-based fallback values. +When a base atom selects a local math-family font, its MATH script scale-down, +script and operator-limit constants, italic correction, and MathKern data now +come from that face when available; missing MATH data falls back to the +configured metrics font. +All eight TeX math styles are represented, including cramped variants. Fraction +numerators and denominators now receive their separate `num_style` and +`denom_style`; radical and overline nuclei use cramped style, and subscript and +superscript children use their respective style transitions. Cramped +superscripts read the OpenType `SuperscriptShiftUpCramped` constant. +Unruled fractions such as `\\atop` and `\\choose` use `StackTopShiftUp` and +`StackBottomShiftDown` in text style. Display style follows XeTeX's `num1` and +`denom1` defaults and uses the fraction display-shift constants. The minimum +stack gap comes from the MATH table; without one, it falls back to three rule +thicknesses in text style and seven in display style, following XeTeX's +`make_fraction` path. Fractions rebox the numerator and denominator to the +larger child width without added horizontal padding. MATH +rule thicknesses are used as stored; without a MATH table, the engine uses a +0.04 em default rule and TeX's one-rule or three-rule per-side clearance. +For a single-glyph base, the layout reads per-glyph OpenType `MathKernInfo` +corner tables from the face used to draw each glyph. Script lookup follows +XeTeX's first-character scan: it skips leading math spaces, applies style +changes, selects the active `\\mathchoice` branch, and uses the first character-like +glyph even when the script continues with more content. It stops when the +script starts with a box or a non-character expression. The layout measures +the actual glyph bounds, evaluates both opposing-edge sums after vertical +placement, and chooses the numerically larger correction as XeTeX does. A +composite base, a boxed script nucleus, or missing MATH data retains the +default script offset. See the [XeTeX math-list algorithm](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/web2c/xetexdir/xetex.web) +and [XeTeX OpenType math-kern implementation](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/web2c/xetexdir/XeTeXOTMath.cpp). +Correction heights equal to a table transition use the kern range that begins +at that height, following the OpenType MATH interval rule. +Because this correction is stored in the shared math box, PDF and SVG use +identical positions. +SVG and PDF use the same rule geometry. These rules follow the algorithms +documented in the primary [TeX engine source](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/web2c/tex.web). +Math font switches for `\\mathbf`, `\\mathit`, `\\mathrm`, and `\\text` now +remain explicit nodes in the math tree. The same styled nodes feed PDF and SVG +layout, so bold, italic, and upright math select matching embedded font faces. +`\\overline` and `\\underline` now become two-dimensional accent boxes with +separate bar and nucleus positions. Their vertical gaps, rule thickness, and +reserved ascender/descender space come from the OpenType MATH table when +available; the fallback still lays the bars as rules above or below the body. +`\\hat`, `\\tilde`, `\\widehat`, `\\widetilde`, `\\overbrace`, and +`\\underbrace` are typed accent nodes. The narrow hat and tilde use fixed +math-font glyphs, while the wide variants and braces grow through horizontal +OpenType MATH variants and assemblies. Accent boxes keep the nucleus width, +allowing the painted glyph to overhang as in XeTeX. Top accents use the MATH +`AccentBaseHeight` (or the text font's x-height without a MATH table) and retain +the painted glyph baseline. Single-glyph bases and accent glyphs use their +`TopAccentAttachment` values when available. Accent bitmaps use the same +positions in PDF and SVG; faces without a construction use their available +accent glyph. +The math layout reads OpenType MATH constants for its axis, fraction, script, +radical, radical-degree, and delimiter dimensions when a MATH font is available. +It searches common TeX Live paths for STIX Two Math, New Computer Modern Math, +then STIX Math; setting `TEXRRA_MATH_METRICS_FONT` selects a specific face. +This uses the constants described in the +[OpenType MATH specification](https://learn.microsoft.com/en-us/typography/opentype/spec/math). +If none of those faces is available and no override is set, the compiler falls +back to Liberation Serif metrics. Vertical `\\left...\\right` +delimiters select the first MATH glyph variant large enough for the TeX math-axis +target; if no variant fits, the compiler adds extender parts from the font's +vertical assembly when needed, then distributes connector overlap evenly to +match the target, as described by OpenType MATH. PDF and SVG use the +same antialiased 600-dpi delimiter bitmap. +Math atom outlines are rasterized at 600 dpi and shared by the SVG and PDF +renderers. A loaded MATH face supplies single-symbol operators, relations, +delimiters, punctuation, Unicode Greek letters, and non-alphanumeric +ordinary-class symbols. Default math-italic Latin letters also use that face +when the glyph is available, so their advances, italic corrections, MathKern, +vertical bounds, and accent attachments come from the face used to paint them. +Bold, roman, and text styles use their corresponding Liberation Serif face. +Rasterized atoms derive their box height and baseline from the selected glyph +bounds while keeping its advance as the horizontal math width; text fallbacks +retain the configured font's line metrics. Lowercase Greek letters use the +italic math family, while +uppercase Greek letters use the current math family, following TeX's default +mathcode behavior. SVG keeps these images transparent; PDF composites them onto +white because this PDF backend cannot encode alpha images reliably. Unavailable +or non-outline glyphs fall back to text. Math atoms outside the ordinary class +select upright math style. Display-style single-glyph operators try OpenType +MATH vertical variants and assemblies with a target height of +`max(DisplayOperatorMinHeight, 1.25 × original glyph height)`, following +XeTeX's `make_op`. When the font has no usable construction, the original glyph +keeps its normal size. Delimiters without a usable MATH variant or assembly use +the original glyph's advance and ink bounds, then center its box on the math +axis instead of scaling a text glyph to fit the contents. Math alignment tabs and typed row-break events +now produce a two-dimensional cell grid. `aligned` columns alternate right and left alignment +with an inter-pair gap; `alignedat` and `alignat` use the same column alignment +without automatic gaps and consume their column-pair count. Matrices and +`gathered` center cells; `cases` left-aligns cells; and `array` accepts simple +`l`, `c`, and `r` columns, repeated column patterns, and vertical rules. Matrix environments add paired delimiters; +matrix and array cells use text style, while `smallmatrix` uses script style and +thick-space column gaps. `aligned`, `alignedat`, and `gathered` cells use display +style. Array rows use their measured cell struts, `cases` stretches those struts +by 1.2. Display alignments use the grouped `\jot` dimension (default 3 pt), +captured on the typed environment-start event and carried into the shared math +box layout, so local and global assignments affect subsequent alignments and +invalidate the relevant math parse key. Unstarred +`equation`, `align`, `alignat`, `flalign`, `eqnarray`, `gather`, and `multline` +environments advance a shared equation counter. `multline` lays out its first +row flush left within the full display width, its final row flush right, and +intervening rows centered; it receives one equation number on its final row. +Alignment rows can carry independent numbers, manual `\tag{...}` values or +unparenthesized `\tag*{...}` values, +`\nonumber` / `\notag` suppression, and `\label` references. The PDF renderer +and HTML preview place tags against the same math row baselines when tags fit, +so numbering follows the shared two-dimensional math layout. Tag widths are +measured before placement, with amsmath's half-quad +`\mintagsep` minimum gap ([package documentation](https://tug.ctan.org/macros/latex/required/amsmath/amsmath.pdf)) reserved to prevent a long tag from +overlapping a centered formula; multline reserves that space on the tagged +side. Each row is checked independently; a colliding tag gets a line directly +below its formula row, and later rows move down by the inserted line height. +This follows the row-specific layout model without reproducing all of amsmath's +tag and alignment adjustments. PDF and HTML preview share the same computed +tag positions and measured height. Starred +environments remain unnumbered unless a row has an explicit tag. Full +`amsmath` behavior and OpenType math shaping for ordinary symbols and operators +remain incomplete. + +## XeTeX source and licensing + +XeTeX is open source and its implementation is now a direct behavioral +reference for the Rust rewrite. The XeTeX upstream notes that its engine sources +live under `source/texk/web2c/xetexdir`. XeTeX portions carry MIT-style +permission, while `xetex.web` also includes a separate e-TeX notice restricting +copying that material. TeX Live as a whole has no single license. Each ported +slice must record its upstream file and applicable notice; do not infer a +license for one file from another. The engine is being restructured in Rust +around incremental phases; it is not a mechanical translation of the legacy +tree. See +the [XeTeX source +notes](https://github.com/TeX-Live/xetex/blob/master/INSTALL), [XeTeX copying +notice](https://raw.githubusercontent.com/TeX-Live/xetex/master/source/texk/web2c/xetexdir/COPYING), +and [TeX Live license information](https://github.com/TeX-Live/installer/blob/master/LICENSE.TL). + +No XeTeX source has been copied into this repository as part of the current +milestone. The implementation remains a limited LaTeX subset. Runtime scanning +for the document, compatibility prelude, `\input` files, and `.sty` sources +now uses `texrra-core::mouth` through the `engine::mouth` compatibility +re-export. Texlang still owns the main VM loop and primitive execution, plus +some stdlib input paths such as `\read`. +`vendor/texlang` now has a lazy external-input adapter that preserves VM +expansion frames for nested sources, alongside its earlier brace-group hooks; +its upstream license is retained there. The expanded output retains +source-spanned tokens and typed events, and both document parsing and +math-expression parsing consume them. The compatibility serialization remains +for text-range copying, VM source mapping, and incremental checkpoint slicing. +The next core step is to replace Texlang's main execution loop and fallback +primitive dispatch with an engine-owned token interpreter, then generalize the +Rust-owned text page frames into shared engine lists and a positioned page tree. +`src/rust_typeset/page_builder.rs` is a behavior reimplementation of the +fixed-box page-break slice in XeTeX's `xetex.web`; it does not copy source text +and does not yet model the full page-builder state machine. diff --git a/docs/xetex-rust-port-map.md b/docs/xetex-rust-port-map.md new file mode 100644 index 0000000..0e8ce76 --- /dev/null +++ b/docs/xetex-rust-port-map.md @@ -0,0 +1,357 @@ +# XeTeX core port map + +## Target + +Rewrite the XeTeX engine in Rust and use XeLaTeX as the compatibility oracle: +the same LaTeX format, package inputs, fonts, and document should produce +equivalent diagnostics and page layout. Then add Typst-style dependency +tracking and incremental recomputation around stable TeX state boundaries. +The current Rust compiler is a running subset and migration host; it is not yet +that rewrite. The target is to move the live execution and layout path into +project-owned Rust modules, rather than grow the existing subset indefinitely. + +XeTeX and LaTeX are separate compatibility layers. XeTeX supplies TeX's +execution and typesetting engine plus Unicode and modern-font support. The +LaTeX format and packages define document-level commands on top of that +engine. Rewriting the engine does not automatically implement the package +ecosystem. + +## Migration contract + +The target is observable XeLaTeX behavior across the engine, the selected +LaTeX format, package inputs, and fonts. PDF object bytes do not need to match; +page dimensions, line and page breaks, glyph selection and placement, references, +and source-located errors do. + +Typst's phase boundaries and incremental reuse are architectural references. +TeX still executes tokens against mutable state, so cached work is reusable only +when the incoming engine state and every dependency are unchanged. The Rust +engine's semantic output must be built from TeX modes and native horizontal, +vertical, and math lists. A command is not a completed engine port merely because +it has a parser event or a PDF drawing branch. + +New engine behavior belongs behind project-owned token, state, expansion, +primitive, and list interfaces. Texlang remains a temporary compatibility +adapter while those interfaces are migrated; it must not define the long-term +engine state or execution contract. The current `DocumentModel` renderer stays +available during the transition, but it is not the target TeX intermediate +representation. + +## Upstream reference + +- XeTeX engine source: `texk/web2c/xetexdir/xetex.web` in the [TeX Live + source mirror](https://github.com/TeX-Live/texlive-source/tree/trunk/texk/web2c/xetexdir). +- Base TeX engine source: [`tex.web`](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/tex.web). +- XeTeX source tree and build description: [TeX-Live/xetex](https://github.com/TeX-Live/xetex). +- XeTeX's `xetexdir/COPYING` and the header of `xetex.web` contain MIT-style + permission for XeTeX portions, with notice-retention requirements. The same + `xetex.web` header also includes a separate e-TeX notice that restricts + copying that material. TeX Live is a collection with package-specific + licenses, so record the exact upstream file and applicable notice for every + ported slice; do not assume the whole source tree shares one license. + +## Current dependency boundary + +| Engine responsibility | Current implementation | Rewrite boundary | +| --- | --- | --- | +| Semantic document IR and parsing | `texrra-core::document` owns document metadata, source-anchored blocks, text/math runs, tables, lists, unresolved references, and page settings. `texrra-core::document_parser::parse_document` consumes the source-mapped expanded stream; `texrra-core::references` resolves labels and citations over the resulting IR, and `CompilerSession` invokes both core phases directly. The application document and parser modules remain compatibility re-exports; PDF and HTML use the core types. | Reuse semantic nodes across edits using source identity and dependency-aware invalidation; the parser and its paragraph cache are core-owned, but a source edit still traverses the document. | +| TeX input, tokens, macro expansion, primitive execution | `texrra-core::mouth` owns runtime scanning for the document, compatibility prelude, `\input` files, and `.sty` sources. It now emits the shared `EngineTokenValue` plus a source span; `engine::mouth` is a compatibility re-export, and conversion to VM tokens happens in the adapter. `texrra-core::source` owns source origins and locations independently of Texlang; `texrra-core` also owns `EngineToken`, token values, control-sequence names, category-code and math-code types, plain TeX catcode defaults, macro definitions, argument matching, replacement instantiation, scoped macro tables, assignment scope, environment stack, and native-command meanings independently of Texlang's interned IDs. The application modules `engine::token`, `engine::macros`, and `engine::expansion` are compatibility re-exports; Texlang re-exports the shared category-code and math-code types as a compatibility API. `texrra-core::mouth::CatCodeTable` stores and scopes catcodes directly. `texrra-core::math_code::MathCodeTable` owns ordinary math codes, while `texrra-core::math_code::UnicodeMathCodeTable` and `texrra-core::math_code::DelimiterCodeTable` hold Unicode math codes and delimiter registrations; math token lowering and the `\mathcode`, `\Umathcode`, and `\delcode` adapters use these engine-owned tables and their local/global save stacks. The Texlang variable adapters opt out of the VM save stack for these engine-owned values. `texrra-core::environment::EnvironmentStack` owns serialized LIFO environment state and rejects mismatched `\end` operations. `texrra-core::assignment_scope::AssignmentScope` owns the scoped `\globaldefs` value and resolves local/global assignment scope. `texrra-core::macros::MacroTable` owns macro names, parameter prefixes, delimiters, and replacement token values; `texrra-core::expansion` matches arguments through an engine-owned token-stream interface and instantiates replacements. A Texlang adapter hook consults the macro table before command-map lookup in both normal expansion and `expand_once`; command-map entries remain reflection markers for primitives that inspect meanings. Engine tokens carry source-trace IDs; a bridge table maps those IDs to Texlang trace keys for source diagnostics. `\read` streams and a few lower-level stdlib paths still use Texlang's lexer. | Replace the remaining Texlang expansion stream, primitive dispatch, variable, grouping, and error contracts with engine-owned semantics, while keeping a per-phase comparison path against XeTeX. | +| Registers, dimensions, and glue | `engine::registers::RegisterTable` owns sparse `\\count`, `\\dimen`, `\\skip`, `\\muskip`, and `\\toks` values plus local/global group history. Their `\\countdef`, `\\dimendef`, `\\skipdef`, `\\muskipdef`, and `\\toksdef` aliases bind to those tables. `texrra-core::integer` owns signed, octal, hexadecimal, character-constant, and internal-value integer scanning; `\\penalty`, register indices, and expression factors use it through the adapter. `engine::dimension` scans explicit dimensions and glue for `\\kern`, `\\hskip`, `\\vskip`, `\\above`, and `\\abovewithdelims`; it evaluates e-TeX `\\dimexpr` and `\\glueexpr` arithmetic using the shared integer scanner. Other internal-value forms retain a Texlang parser fallback. `engine::arithmetic` owns command dispatch and arithmetic semantics for `\\advance`, `\\multiply`, and `\\divide` over typed integer, dimension, glue, and math-glue variables. `engine::variable` owns assignment parsing and writes for arithmetic variables, including small integers; Texlang still supplies variable descriptors and dynamic index resolution. Texlang typed parsers for integers, dimensions, ordinary glue, and math glue delegate to Rust scanner hooks for assignments and arithmetic operands. The Rust dimension scanner also backs `\\kern`, `\\hskip`, and `\\vskip`; non-arithmetic assignments and other internal-value forms retain the Texlang compatibility path. `texrra-core::glue::TeXGlue` owns stretch/shrink fields and infinity orders; `engine::glue` re-exports it at the adapter boundary. Fixed-point storage still uses `common::Scaled`. | Move remaining internal-value parsing, variable access, and fixed-point representation into the engine; keep conversions at backend edges. | +| Paragraph breaking and font metric repository | `boxworks`, `boxworks-knuthplass`, `rusttype` | Port TeX's list and line-breaking behavior; isolate font metric/shaping providers behind engine interfaces. | +| Math parsing and much of 2D math layout | `texrra-core::expanded` owns the source-mapped expanded token/event stream; `texrra-core::math_mode` validates math scope transitions and math-only events; `texrra-core::math_lowering` converts math delimiters, validates and lowers math environments, builds equation rows, and caches parsed expressions; `texrra-core::math_parser` consumes the stream into `texrra-core::math_expr::MathExpr`; `texrra-core::math_style` owns the eight TeX math styles and child-style transitions; `texrra-core::math_list` owns style-sensitive class boundaries, `\\mathchoice` selection, binary-operator normalization, the eight-class spacing table, and style-aware math-skip selection; `texrra-core::math_alphabet` selects Unicode math alphabets and rewrites ordinary atoms through nested expressions; `texrra-core::math_constants` parses OpenType MATH constants and selects fraction, script, operator-limit, radical, and bar parameters; `texrra-core::math_layout` owns math-sequence state planning and measured child placement plus fraction-box, ordinary script, display-limit, radical-box, delimiter-target, ordinary delimited-box, fenced-row, accent, alignment, display-row, `multline`, and equation-tag geometry; the application supplies measured glyphs and font-availability queries, converts mu to page units, and assembles delimiter glyphs | Move glyph access and font metric queries behind core layout interfaces; compare noad construction, style transitions, math alphabets, MATH constants, and glyph selection against XeTeX. | +| Page breaking | `page_builder.rs` plus a restricted positioned-page path in `pdf.rs`; page-break badness now follows TeX's integer approximation from `tex.web`, and `\\vskip` glue enters the vertical node list | Extend from fixed boxes/glue/penalties to engine-owned vertical lists, insertions, output routines, and page frames. | +| PDF assembly and page composition | `genpdf` | Make an engine-owned positioned page tree the source for PDF and live preview; retain only a replaceable PDF serialization backend. | +| Font table access and images | `ttf-parser`, `image` | Keep format parsers as replaceable I/O components; define shaping, metrics, and asset contracts in the engine. | + +The core now selects math-atom glyph text, font preference, and atom slant, and +interprets OpenType MATH per-glyph italic corrections, top accent attachments, +and height-dependent corner-kern selection through +`texrra-core::math_glyph` and its engine-owned `MathGlyphMetrics` and +`MathKernTable` values. The application maps core slants to backend styles and +converts parsed OpenType records into these values; font opening, +character-to-glyph lookup, page-unit conversion, glyph bounds, outlines, and +delimiter assembly remain in the application backend. +`texrra-core::math_layout::math_script_kern` selects the larger of XeTeX's +two candidate horizontal kern sums for ordinary subscripts and superscripts +using those backend-provided glyph measurements. Nucleus classification for +character scripts, single-glyph operators, and operator limits now resides in +`texrra-core::math_expr` and is consumed by the application layout adapter. +`texrra-core::math_alphabet` also owns the Unicode mappings and recursive +expression rewrite for TeX math alphabets; the application provides selected- +font and default-math-font glyph-availability queries. The script-kern adapter +uses the core's first-nucleus traversal, while the backend still resolves the +font face and glyph outline. +`texrra-core::math_layout::plan_math_sequence` resolves each item's active +math style, spacing settings, class boundary, and nested-list context. +`layout_math_sequence` arranges measured child boxes around their shared +baseline and returns backend-neutral positions; PDF code now only measures +children and converts those positions to its page units. +`CompilerSession` reuses the active `MathFontMetrics` across edit compiles and +PDF/HTML renders when the selected font files have unchanged contents; cloned +metrics share extracted glyph data keyed by font-byte identity and character. + +## Port order + +The runtime source stack and TeX file-name scanning now live in +`texrra-core::input`; `engine::input` is a compatibility re-export. +Tokenization is implemented in `texrra-core::mouth` and re-exported +through `engine::mouth`. The core owns source frames, tokenized macro +replacement frames, text, line offsets, input priority, TeX filename splitting, +and `InputFileLocation::resolve_path`. +`CompilerState` supplies the working directory, performs file reads and +records dependencies, and keeps Texlang diagnostic trace mapping at the +adapter boundary. `\\input` and `\\endinput` now dispatch +through project-owned primitives and push or end those engine frames. The Rust +`scan_file_location` follows XeTeX's [`more_name`](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L11244-L11255) +and [`scan_file_name`](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L11420-L11431) +rules. The filename scanner receives expanded tokens through its adapter; +path resolution uses the Rust-owned `InputFileLocation::resolve_path`, while +the adapter performs file reads and records dependencies. It passes resolved +source text when pushing +the nested input frame. File areas are reported as a source-located error +instead of reaching Texlang's panic path; area-to-directory mappings remain +unimplemented. + +`texrra-core::layout_primitive` owns the primitive set, action selection, +operand scan order, and typed effect contract for `\\par`, `\\newline`, +`\\pagebreak`, `\\penalty`, `\\kern`, `\\hskip`, and `\\vskip`; +`engine::layout_primitive` is a compatibility re-export. The Texlang adapter +supplies the concrete token cursor and numeric scanners, then translates core +effects into source-located output events. +`texrra-core::command::NativeCommandTable` owns the meanings for these +layout primitives, `\\advance`, `\\multiply`, `\\divide`, and the `\\global`, +`\\long`, `\\outer`, and `\\relax` prefix primitives. The patched VM tag still +routes those tokens into the adapter. `EngineSemanticState::command_meaning` +resolves macro meanings before native meanings, and both expansion and +execution hooks use that shared lookup. `\\let` copies native meanings into +scoped aliases; macro definitions clear any native meaning they shadow. The +VM's main execution loop and other primitive dispatch remain to be replaced. + +The engine now owns the explicit-token scan for dimensions and glue. It reads +decimal, octal, and hexadecimal numeric forms; the standard physical units; +`em`/`ex`; `true` magnification; `fil`, `fill`, and `filll` glue orders; and +parenthesized e-TeX `\\dimexpr`/`\\glueexpr` arithmetic with `+`, `-`, `*`, `/`, +and `\\relax` termination. The project adapters still supply expanded tokens +and diagnostics. `em`/`ex` still use Texlang's default 12 pt metrics because +Rust font metrics are not connected yet. Magnification is owned by the Rust +engine at its default value of 1000 and is passed into this scanner for `true` +dimensions. The Rust scanner parses decimal, octal, hexadecimal, and +character-constant integers for +register indices and expression factors, and reads native typed register +variables directly from engine state. Active `\\count`, `\\dimen`, `\\skip`, +`\\muskip`, and `\\toks` values and all five `*def` aliases use Rust-owned +sparse tables and group history; the VM register components have been removed +from `CompilerState`. Other internal-value forms still fall back through +Texlang's parser API. Prefix scope for aliases is applied to the command-map +definition and consumed there, so it cannot leak into a later register +assignment. +Expression precedence, +parentheses, and scaled-point rounding use XeTeX's e-TeX +[`scan_expr`](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L30425-L30743) +as the behavior reference. +This is the first numeric-scanning port, not a claim that TeX's full +`scan_dimen` contract has moved. The compatibility reference is XeTeX's +[`xetex_scan_dimen` and `scan_glue`](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L9721-L10015), +which inherit the base TeX scanner and add XeTeX-specific behavior. +The engine now owns `\\mag` (default 1000) and feeds it to the Rust scanner +for `true` dimensions. Global PDF/page scaling and XeTeX's magnification-freeze +behavior are still outside this slice. + +1. **Execution state:** source input stack, token scanner, category codes, + control-sequence table, grouping/save stack, registers, and recoverable TeX + errors. Migrate one primitive family at a time from `texlang` while the old + path remains available for comparison. +2. **TeX lists and modes:** horizontal, vertical, and math modes; boxes, glue, + kerns, penalties, insertions, and math noads. These are the engine's shared + intermediate representation, not document-parser marker events. +3. **Typesetting algorithms:** paragraph line breaking, math-list conversion, + page building, and output routines over those lists. Compare dimensions, + break choices, and diagnostics with XeTeX fixtures. +4. **Fonts and shaping:** Unicode font selection, OpenType MATH data, shaping, + script runs, and glyph positioning. Keep font file decoding separate from + TeX's font and layout decisions. +5. **Output and live compilation:** export one positioned page tree to PDF and + preview. Cache phase results only where the incoming TeX state is part of + the cache key; edits to macros, registers, catcodes, or package inputs must + invalidate dependent work. +6. **LaTeX format and packages:** load the format and expand package support on + the completed engine. Track package behavior separately from engine + primitives. + +## Port acceptance record + +Each ported behavior needs a small record containing the XeTeX source section +or algorithm reference, input fixture, expected token/list/box result, +diagnostics, font assumptions, and observed XeLaTeX output. Compare generated +PDF pages and diagnostic locations, not just whether a command name is +recognized. Keep the same TeX Live format, packages, and fonts on both sides so +the comparison isolates engine behavior. Unsupported cases must be identified +as such while the live application remains runnable during migration. + +The fixed-box page breaker uses the integer `badness` approximation in the +`badness` routine of [`tex.web`](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/tex.web#L2118-L2145). This preserves TeX's discrete page-break costs where the previous floating-point approximation could select a different candidate near a tie. `engine::dimension` now scans explicit `\kern` dimensions and `\hskip`/`\vskip` glue, then carries those values into horizontal runs or vertical page nodes; token-level internal-value scanning still uses the compatibility parser over Rust-owned `\dimen` and `\skip` tables. Horizontal kerns participate in text and inline-math line layout; vertical kerns participate in page breaking and positioned output. Leading vertical kerns are discarded with other top-of-page material, following [`vert_break`](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L17307-L17392). `texrra-core::math_mode::validate_math_delimiters` validates inline/display math scopes, matching closes, `\tag` placement, and `\par` inside math. Outer vertical/horizontal transitions remain in the application builder, and the page builder still lacks TeX's output routine, insertions, and complete vertical-list execution. + +## Current rewrite status + +`CompilerState` now delegates engine semantics to +`texrra-core::state::EngineSemanticState` through the `TeXEngineState` +adapter: catcodes, math codes, assignment scope, macros, native-command +meanings, environments, and group save/restore live in the core. The adapter +retains source I/O and register values that still use Texlang types. Texlang +still owns the main execution loop and fallback dispatch, so this is a concrete +Rust-core extraction step rather than a completed XeTeX rewrite. + +The project-owned primitive map now handles `\\par` and `\\newline` directly: +they emit typed paragraph and line-break events without routing through the +Texlang script-output component or compatibility-prelude aliases. +`texrra-core::math_lowering` calls the core math-scope validator before +constructing expression trees. Outer vertical and horizontal mode transitions +remain outside the core. + +The math tree now distinguishes first-row baselines for top-level display +alignments from math-axis-centered baselines for nested alignment and matrix +boxes. An outer `equation` preserves an inner `aligned`, `split`, matrix, or +array node. The axis height uses the family-2 font selected for the active math +style when that font has an OpenType MATH axis constant, and falls back to the +configured default metric otherwise. This follows XeTeX's `make_vcenter` +baseline contract. The frontend captures the math-family table when the +environment begins, so the axis metric comes from family 2 at the environment's +entry state instead of being inferred from whichever font appears in a cell. + +The Rust math path also parses XeTeX's infix fraction variants `\\over`, +`\\atop`, `\\choose`, `\\above`, `\\overwithdelims`, `\\atopwithdelims`, +and `\\abovewithdelims`. Delimiter variants carry both scanned glyphs and +sizing settings through the typed event stream, then use the shared scalable +delimiter layout around the same fraction node. XeTeX scans both delimiters +before the explicit dimension in `\\abovewithdelims`, matching the Rust +scanner order ([source](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L24875-L24904)). +Ruled fractions center the bar on the font's `AxisHeight`; the fraction box +accounts for half the rule thickness on each side, so OpenType MATH minimum +gaps are measured to the bar's ink edges ([MATH constants](https://learn.microsoft.com/en-us/typography/opentype/spec/math)). + +Inline math uses the paragraph's Knuth–Plass line breaker. The expanded stream +snapshots `\binoppenalty` and `\relpenalty` (defaults 700 and 500) so +assignments affect only subsequent math atoms. Break penalties follow binary +and relation noads; punctuation does not add a breakpoint, and a penalty is +suppressed immediately before a relation noad, following XeTeX's math-list +conversion ([`xetex.web`](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web)). +`texrra-core::math_list::plan_inline_math` now owns the per-sequence style +and math-skip state, explicit math glue and penalties, and automatic binary or +relation break decisions. It returns a backend-neutral plan containing formula +expressions, active styles, nested-list contexts, mu glue, and break penalties; +the application measures formulas, converts mu units, and feeds Knuth–Plass. + +The `\penalty` primitive now emits a typed penalty event. In inline math it +becomes a zero-width math-list node; in Rust-owned paragraph layout it becomes +a horizontal penalty, and in vertical mode it is passed to the Rust page +breaker, following the penalty-node handling in [`tex.web`](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/tex.web). The compatibility +macros `\allowbreak` and `\nobreak` expand to penalties 0 and 10000. An +explicit penalty immediately after a relation or binary noad supersedes the +automatic break penalty there. + +Horizontal `\\hskip` scans a full glue value, including `plus`/`minus` +amounts and `fil` orders. `texrra-core::glue::TeXGlue` is the engine-owned +value used by paragraph and math lists; `engine::glue` re-exports it for +existing scanner code. Explicit horizontal glue +stretches or shrinks with its line and retains TeX's glue-order priority. +Vertical `\\vskip` also scans a full glue value and passes width, stretch, +shrink, and orders to the Rust page breaker. Positioned pages currently use its +natural width; page-level glue setting and stretch distribution remain to be +ported. + +`crates/texrra-core/src/mouth.rs` owns the TeX input scanner and emits token +values from shared core types; `src/rust_typeset/engine/mouth.rs` is a +compatibility re-export. The core crate also owns category-code and math-code +types, plain TeX category-code defaults, TeX macro definitions and tables, and +macro argument/replacement algorithms. Texlang re-exports the shared +category-code and math-code types as a compatibility API. The scanner handles +line-state transitions, +control-sequence names, comments, ignored and invalid characters, `^^` notation, +and source spans without calling Texlang's lexer. `CatCodeTable` stores the +shared core catcode values and keeps a save stack for local assignments, +clearing saved values on global assignments. The Texlang `\catcode` variable +adapter mutates this same table. `texrra-core::math_code::MathCodeTable` owns the +per-character math-code values, while `texrra-core::math_code::UnicodeMathCodeTable` and +`texrra-core::math_code::DelimiterCodeTable` own Unicode math-code values and delimiter registrations. +Math-token lowering and the Texlang `\mathcode`, `\Umathcode`, and `\delcode` +adapters use the engine tables, which now own local/global assignment saves +and restore them on engine group exit. Their Texlang variable adapters opt out +of the VM save stack, avoiding two competing owners for grouping state. +Group exit restores the shared value once. Brace groups and the +`\begingroup`/`\endgroup` primitives enter and leave the engine stack, so the +live lexer observes active catcodes while reading subsequent source. +The `\endlinechar` variable now reads and writes the same engine-owned state; +the table preserves its value across local groups and clears saves for global +assignments. +The mouth treats values from 0 through 255 as active character codes, matching +XeTeX's `end_line_char_inactive` check in [`xetex.web`](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L8113-L8114). +`texrra-core::assignment_scope::AssignmentScope` owns `\globaldefs` and its group +save stack, and selects assignment scope. The engine-owned tables record the +old values for `\catcode`, `\endlinechar`, ordinary/Unicode math codes, and +delimiter codes; `EngineSemanticState` opens and restores these scopes with +each group. Scope selection applies positive `\globaldefs` values globally, +negative values locally, and zero uses the prefix command, following +the `globaldefs` adjustment in [TeX's `prefixed_command`](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/tex.web#L20854-L20860). +`engine::prefix` now scans `\global`, `\long`, and `\outer`, skips intervening +spaces and `\relax`, and validates targets from the command registry's tags. +The command registry remains the dispatch adapter. The prefix scanner validates +`\long` and `\outer` placement and stores those flags on engine macros. +Non-long macro argument scanning rejects `\par`, with the delimited-parameter +exception for a partial delimiter match; outer macros are rejected in Rust +macro-argument scans, shared braced/optional argument scans, generic Rust +token-list scans, and expanded definitions. The token-list adapter checks its +captured unexpanded tokens and preserves the existing token-register path. +Outer checks in other TeX scanner contexts remain to be ported. +Unstarred `\newcommand` definitions are long; starred +definitions are non-long. These rules follow TeX's [`long_state` argument +scanner](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/tex.web#L7481-L7491) +and [outer-token check](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/tex.web#L6826-L6832). +The `\bgroup`/`\egroup` compatibility macros use the same group path. +The vendored command map has a local save stack for control-sequence and active +character definitions. Local assignments restore at group exit; global +assignments clear saved values across open groups. Active-character meanings +are included in serialized VM snapshots. +The checkpoint scanner uses the project-owned mouth for whitespace, comments, +control-sequence, and `^^` tokenization. Both preamble-start discovery and +body checkpoint discovery use it. It models direct decimal and backtick-character +`\catcode` assignments and direct signed-decimal/backtick `\endlinechar` +assignments with the same local/global save stack as runtime state. Body +checkpoints are placed at top-level paragraph tokens; discovery still stops +adding later checkpoints around `\globaldefs`, primitive definitions, and +verbatim-like environments. Catcode and `\endlinechar` changes hidden inside +arbitrary macro expansion are not visible to this locator, so preamble +checkpoint detection remains a heuristic. + +The document, compatibility prelude, `\input` files, and `.sty` files now use +the project-owned mouth at runtime. `\newcommand`, `\renewcommand`, +`\providecommand`, `\def`, and `\gdef` definitions are stored in the +engine-owned `MacroTable`; `texrra-core::macros` scans the target, parameter +text, and grouped replacement body through a generic token-stream interface, +then parses parameter prefixes, sequential numbered parameters, delimiters, +and replacement references. `texrra-core::expansion` scans and substitutes arguments. +The Texlang adapter supplies the unexpanded token stream and maps engine +diagnostics back to source tokens. +`\let` copies engine-owned macro meanings as well +as ordinary command meanings. `\edef` / `\xdef` expand replacement tokens +inside a bounded input list and store the resulting definitions in the same +Rust table. These definitions follow local and global grouping scope. The table +stores macro names and parameter-matching token values independently of +Texlang's interned control-sequence IDs. Texlang invokes a Rust macro-expansion +hook before command lookup for both ordinary expansion and `expand_once`, so +the engine table decides macro expansion. Command-map entries remain reflection +markers for primitives that inspect command meanings. Replacement bodies and +scanned arguments use engine-owned `EngineToken` values with numeric trace IDs; +a separate adapter table maps those IDs to Texlang trace keys when producing +source diagnostics. Parameter matching, argument scanning, and replacement +instantiation operate only on engine token values in `texrra-core`. The +Texlang bridge converts tokens at the unexpanded-input +boundary and converts completed replacement tokens back before placing them on +the VM expansion stack. Primitive dispatch and `\read` still use Texlang paths. Runtime +`\begin` / `\end` now use the serialized engine-owned +`EnvironmentStack`; a mismatched close is rejected before its event reaches +document parsing. Non-document environments use the engine save stack for +local assignments. This is a first execution migration, not a replacement for +Texlang's general primitive expansion, execution loop, or primitive dispatch. +The current typesetting layout remains a subset. The next execution boundary is +to move remaining expandable primitives, assignments, and error handling +behind engine-owned state while preserving a comparison path against XeTeX. diff --git a/examples/boxes.tex b/examples/boxes.tex new file mode 100644 index 0000000..4a56265 --- /dev/null +++ b/examples/boxes.tex @@ -0,0 +1,24 @@ +\documentclass{article} +\begin{document} + +\section*{Box material demo} + +A framed box: \fbox{Hello box}. An inline unbreakable box: +\mbox{alpha beta gamma} stays together. + +\parbox{60mm}{This parbox wraps its content to a sixty millimetre +column and sits in the vertical flow without a frame.} + +\begin{center} +Centered text +\end{center} + +\hrule + +\smallskip +After a small skip. + +\bigskip +After a big skip: {\bfseries bold}, {\itshape italic}, {\ttfamily mono}. + +\end{document} diff --git a/examples/compat.tex b/examples/compat.tex new file mode 100644 index 0000000..04b9dd9 --- /dev/null +++ b/examples/compat.tex @@ -0,0 +1,35 @@ +\documentclass{article} +\begin{document} + +\section*{Compatibility examples} + +Spacing: A\quad B\qquad C, A\thinspace B\enspace C. + +Symbols: \S\P\dag\ddag\copyright\textbullet\textregistered\texttrademark +\ldots\textendash\textemdash\guillemotleft x\guillemotright +\texteuro\textsterling\textyen\textdegree\textpm. + +Letters: \ss\ae\AE\oe\OE\aa\AA\o\O\l\L\i. + +Styles: {\bfseries bold}, {\itshape italic}, {\ttfamily mono}, \textsc{small caps}. + +Breaks: A\nopagebreak[4] B\linebreak[2] C\samepage. + +A\vspace*{6pt} B + +\vspace{6pt} + +A\hspace*{1cm}B + +\begin{center} +Centered text +\end{center} + +\hrule + +\fbox{Framed box} and \mbox{unbreakable box}. + +\parbox{60mm}{A parbox wraps its content to sixty millimetres and stays +in the vertical flow.} + +\end{document} diff --git a/examples/hello.tex b/examples/hello.tex new file mode 100644 index 0000000..04b9dd9 --- /dev/null +++ b/examples/hello.tex @@ -0,0 +1,35 @@ +\documentclass{article} +\begin{document} + +\section*{Compatibility examples} + +Spacing: A\quad B\qquad C, A\thinspace B\enspace C. + +Symbols: \S\P\dag\ddag\copyright\textbullet\textregistered\texttrademark +\ldots\textendash\textemdash\guillemotleft x\guillemotright +\texteuro\textsterling\textyen\textdegree\textpm. + +Letters: \ss\ae\AE\oe\OE\aa\AA\o\O\l\L\i. + +Styles: {\bfseries bold}, {\itshape italic}, {\ttfamily mono}, \textsc{small caps}. + +Breaks: A\nopagebreak[4] B\linebreak[2] C\samepage. + +A\vspace*{6pt} B + +\vspace{6pt} + +A\hspace*{1cm}B + +\begin{center} +Centered text +\end{center} + +\hrule + +\fbox{Framed box} and \mbox{unbreakable box}. + +\parbox{60mm}{A parbox wraps its content to sixty millimetres and stays +in the vertical flow.} + +\end{document} diff --git a/examples/plot.png b/examples/plot.png new file mode 100644 index 0000000000000000000000000000000000000000..ac15fdf9bcea231731137f4785a4016a496f1e4c GIT binary patch literal 1717 zcmZ`)X;c$e6b?gz5ekMa)I<@9ii&_hkX6pGMW|?8Q9u+#VK^+uAc)l>ol;2^B68|c zL<6G%aYqgaf<&-XT9<@GSu`wKC?pbtPyMc?_rC9acbPlioY=H+ovt=b zn?NAw`uTcqArLg)fag9k1nxUb%v1z|);E6M9@`GfRBaD=wDm@5n}6aEOOhaQP5d&$ zOig-mm=E#rk|ojk^JVwmUVfjVT+r5abd6D;)H z_#f_&m83>1s=bGO|H@b=xfIs4R95|#H&G$x@Tf@WluPEQB~HZcaZ|jn+%CV#(qT$0 zL@9Ft(pXv5s=&7P6KTj!`B5mOT55~B=ZfpHv5M{T$o8}@mw7@zC^p0I`oM0-?ws!9 zBN_VTBI+DUNl93z52lf5&0&?n_us4{5@nIukg(RFw9064xmcf_!@+)J~T+!Yt-6}S>BN281_A=Lz>AyD8-bh(Wv zd){ThF>Be`Z{NV&D}@`eyL4{-BRZd^P~2-B|NhQ4!BTo+yU;lc?bXk6Ww%qJ8=N~V z9+N8Be9Ng`;TDF(N3Wn3vN9yK#I`lOGXEmzbUu8;t7~7dWnvlaLXp2e=Cjzm$)p)I zK#I~;R5_*JFUO_Ojgfpjgn#Rq5qfH}c+ffTjJ3U8BO}fuw@>Sk@5CBzp{K~A0KPG= zWRA=p>;5r*%#Lx^mmg(-*bI4_I-o2}*ub!{-^*z@KN-Bh^o~La2bw3cuoXvodFRUE z7sE`~%z%I^$?{G7^Bw6cEsr(Qt5s=+d8F|zsvW}q7j&m@s0hjuEOci`pj*-p)>?m4 z1{gn^V?`+-f)r^81jEZ4eq{#nSe<>-#)D_0YId|aeux$_sJ$|Pg^_{;4zlBqDM(B* z@LNfc($^0?z-cf+BYK1V32TJ%ry}I3-I2J)S5MrWpxALoSq>PwmW~?MFI6{U57tt- zus~XHE+~f-gmEHD9X*LORZU_RAdn(Y(_x1BbbfUarAh9$e$^L%q6}V1zsTg3sQ&&GnhM>!2f$)WGaX&kT!iay`z_>kDztv zrR|>B=0(czWIUc(dMcc%6^PTE`Sk;wN<`}dlV;Gif&v(16&63bN&>nPjDLPv7D;;m zVOIQWz{e_VjV992+{*zyI3o0GFHgLQhuEMtDKerDh$mY1@b!^wMi^)o#5-BB2Ty8$ zPX-)rFKhDvXzs;c9Z1(OVFRC3xeLn#x{_HhudGl<{7f#jr4y~Ma-@#Cu~-f)XTOYz zd)Wb6&$=(dS&{&YSKQFWAv`v0qMPTUgBNT(P$hEFT)KZ5^>@c&ovKL!8m@9?cqt&!-YsygS^z5)D>2!1{r Ky>EMle)kuyztijh literal 0 HcmV?d00001 diff --git a/examples/references.bib b/examples/references.bib new file mode 100644 index 0000000..453d15f --- /dev/null +++ b/examples/references.bib @@ -0,0 +1,20 @@ +@string{ publisher = "Addison-Wesley" } + +@book{knuth1984, + author = {Donald E. Knuth}, + title = {The TeXbook}, + publisher = publisher, + year = {1984} +} + +@proceedings{texrra2026, + booktitle = {Proceedings of the texrra Typesetting Workshop}, + year = {2026}, + organization = {texrra Community} +} + +@inproceedings{texrra-runtime, + author = {Ada Lovelace}, + title = {A Small Live Typesetting Backend}, + crossref = {texrra2026} +} diff --git a/examples/texrra-extra.sty b/examples/texrra-extra.sty new file mode 100644 index 0000000..52ebf3a --- /dev/null +++ b/examples/texrra-extra.sty @@ -0,0 +1,3 @@ +\ProvidesPackage{texrra-extra}[2026/10/17 local preview example] + +\newcommand{\texrranote}[1]{\textbf{Style macro loaded:} #1} diff --git a/fixtures/README.md b/fixtures/README.md new file mode 100644 index 0000000..2f162bc --- /dev/null +++ b/fixtures/README.md @@ -0,0 +1,8 @@ +# Conformance fixtures + +- `arxiv-template/` is George Kour's MIT-licensed arXiv preprint template + (see `arxiv-template/License.txt`). It exercises a real `.sty` file, + `geometry` text-block options, `fancyhdr` no-ops, `\fbox` figures, tables, + references, and Letter paper. +- Compile the fixture by importing it as a project (ZIP upload) or by copying + the directory into `projects/` next to a `.meta` entry. diff --git a/fixtures/arxiv-template/License.txt b/fixtures/arxiv-template/License.txt new file mode 100644 index 0000000..010ba4b --- /dev/null +++ b/fixtures/arxiv-template/License.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 George Kour + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/fixtures/arxiv-template/README.md b/fixtures/arxiv-template/README.md new file mode 100644 index 0000000..6c8cafe --- /dev/null +++ b/fixtures/arxiv-template/README.md @@ -0,0 +1,49 @@ + +## Description: + +The project hosts an aesthetic and simple LaTeX style suitable for "preprint" publications such as arXiv, techrXhiv and biorXiv, etc. +It is based on the [**nips_2018.sty**](https://media.nips.cc/Conferences/NIPS2018/Styles/nips_2018.sty) style. + +This styling maintains the esthetic of NeurIPS but adding and changing features to make it (IMO) even better and more suitable for preprints. +The result looks fairly different from NeurIPS style so that readers won't get confused to think that the preprint was published in NeurIPS. + +### Why NeurIPS? +Because the NeurIPS styling is a comfortable single column format that is very esthetic and convenient for reading. + +## Usage: +1. Use Document class **article**. +2. Copy **arxiv.sty** to the folder containing your tex file. +3. add `\usepackage{arxiv}` after `\documentclass{article}`. +4. The only packages used in the style file are **geometry** and **fancyheader**. Do not reimport them. + +See **template.tex** + +## Project files: +1. **arxiv.sty** - the style file. +2. **template.tex** - a sample template that uses the **arxiv style**. +3. **references.bib** - the bibliography source file for template.tex. +4. **template.pdf** - a sample output of the template file that demonstrated the design provided by the arxiv style. + + +## Handling References when submitting to arXiv.org +The most convenient way to manage references is using an external BibTeX file and pointing to it from the main file. +However, this requires running the [bibtex](http://www.bibtex.org/) tool to "compile" the `.bib` file and create `.bbl` file containing "bibitems" that can be directly inserted in the main tex file. +However, unfortunately the arXiv Tex environment ([Tex Live](https://www.tug.org/texlive/)) do not do that. +So easiest way when submitting to arXiv is to create a single self-contained .tex file that contains the references. +This can be done by running the BibTeX command on your machine and insert the content of the generated `.bbl` file into the `.tex` file and commenting out the `\bibliography{references}` that point to the external references file. + +Below are the commands that should be run in the project folder: +1. Run `$ latex template` +2. Run `$ bibtex template` +3. A `template.bbl` file will be generated (make sure it is there) +4. Copy the `template.bbl` file content to `template.tex` into the `\begin{thebibliography}` command. +5. Comment out the `\bibliography{references}` command in `template.tex`. +6. You ready to submit to arXiv.org. + + +## General Notes: +1. For help, comments, praises, bug reporting or change requests, you can contact the author at: kourgeorge/at/gmail.com. +2. You can use, redistribute and do whatever with this project, however, the author takes no responsibility on whatever usage of this project. +3. If you start another project based on this project, it would be nice to mention/link to this project. +4. You are very welcome to contribute to this project. +5. A good looking 2 column template can be found in https://github.com/brenhinkeller/preprint-template.tex. diff --git a/fixtures/arxiv-template/arxiv.sty b/fixtures/arxiv-template/arxiv.sty new file mode 100644 index 0000000..081d21c --- /dev/null +++ b/fixtures/arxiv-template/arxiv.sty @@ -0,0 +1,262 @@ +\NeedsTeXFormat{LaTeX2e} + +\ProcessOptions\relax + +% fonts +\renewcommand{\rmdefault}{ptm} +\renewcommand{\sfdefault}{phv} + +% set page geometry +\usepackage[verbose=true,letterpaper]{geometry} +\AtBeginDocument{ + \newgeometry{ + textheight=9in, + textwidth=6.5in, + top=1in, + headheight=14pt, + headsep=25pt, + footskip=30pt + } +} + +\widowpenalty=10000 +\clubpenalty=10000 +\flushbottom +\sloppy + + + +\newcommand{\headeright}{A Preprint} +\newcommand{\undertitle}{A Preprint} +\newcommand{\shorttitle}{\@title} + +\usepackage{fancyhdr} +\fancyhf{} +\pagestyle{fancy} +\renewcommand{\headrulewidth}{0.4pt} +\fancyheadoffset{0pt} +\rhead{\scshape \footnotesize \headeright} +\chead{\shorttitle} +\cfoot{\thepage} + + +%Handling Keywords +\def\keywordname{{\bfseries \emph{Keywords}}}% +\def\keywords#1{\par\addvspace\medskipamount{\rightskip=0pt plus1cm +\def\and{\ifhmode\unskip\nobreak\fi\ $\cdot$ +}\noindent\keywordname\enspace\ignorespaces#1\par}} + +% font sizes with reduced leading +\renewcommand{\normalsize}{% + \@setfontsize\normalsize\@xpt\@xipt + \abovedisplayskip 7\p@ \@plus 2\p@ \@minus 5\p@ + \abovedisplayshortskip \z@ \@plus 3\p@ + \belowdisplayskip \abovedisplayskip + \belowdisplayshortskip 4\p@ \@plus 3\p@ \@minus 3\p@ +} +\normalsize +\renewcommand{\small}{% + \@setfontsize\small\@ixpt\@xpt + \abovedisplayskip 6\p@ \@plus 1.5\p@ \@minus 4\p@ + \abovedisplayshortskip \z@ \@plus 2\p@ + \belowdisplayskip \abovedisplayskip + \belowdisplayshortskip 3\p@ \@plus 2\p@ \@minus 2\p@ +} +\renewcommand{\footnotesize}{\@setfontsize\footnotesize\@ixpt\@xpt} +\renewcommand{\scriptsize}{\@setfontsize\scriptsize\@viipt\@viiipt} +\renewcommand{\tiny}{\@setfontsize\tiny\@vipt\@viipt} +\renewcommand{\large}{\@setfontsize\large\@xiipt{14}} +\renewcommand{\Large}{\@setfontsize\Large\@xivpt{16}} +\renewcommand{\LARGE}{\@setfontsize\LARGE\@xviipt{20}} +\renewcommand{\huge}{\@setfontsize\huge\@xxpt{23}} +\renewcommand{\Huge}{\@setfontsize\Huge\@xxvpt{28}} + +% sections with less space +\providecommand{\section}{} +\renewcommand{\section}{% + \@startsection{section}{1}{\z@}% + {-2.0ex \@plus -0.5ex \@minus -0.2ex}% + { 1.5ex \@plus 0.3ex \@minus 0.2ex}% + {\large\bf\raggedright}% +} +\providecommand{\subsection}{} +\renewcommand{\subsection}{% + \@startsection{subsection}{2}{\z@}% + {-1.8ex \@plus -0.5ex \@minus -0.2ex}% + { 0.8ex \@plus 0.2ex}% + {\normalsize\bf\raggedright}% +} +\providecommand{\subsubsection}{} +\renewcommand{\subsubsection}{% + \@startsection{subsubsection}{3}{\z@}% + {-1.5ex \@plus -0.5ex \@minus -0.2ex}% + { 0.5ex \@plus 0.2ex}% + {\normalsize\bf\raggedright}% +} +\providecommand{\paragraph}{} +\renewcommand{\paragraph}{% + \@startsection{paragraph}{4}{\z@}% + {1.5ex \@plus 0.5ex \@minus 0.2ex}% + {-1em}% + {\normalsize\bf}% +} +\providecommand{\subparagraph}{} +\renewcommand{\subparagraph}{% + \@startsection{subparagraph}{5}{\z@}% + {1.5ex \@plus 0.5ex \@minus 0.2ex}% + {-1em}% + {\normalsize\bf}% +} +\providecommand{\subsubsubsection}{} +\renewcommand{\subsubsubsection}{% + \vskip5pt{\noindent\normalsize\rm\raggedright}% +} + +% float placement +\renewcommand{\topfraction }{0.85} +\renewcommand{\bottomfraction }{0.4} +\renewcommand{\textfraction }{0.1} +\renewcommand{\floatpagefraction}{0.7} + +\newlength{\@abovecaptionskip}\setlength{\@abovecaptionskip}{7\p@} +\newlength{\@belowcaptionskip}\setlength{\@belowcaptionskip}{\z@} + +\setlength{\abovecaptionskip}{\@abovecaptionskip} +\setlength{\belowcaptionskip}{\@belowcaptionskip} + +% swap above/belowcaptionskip lengths for tables +\renewenvironment{table} + {\setlength{\abovecaptionskip}{\@belowcaptionskip}% + \setlength{\belowcaptionskip}{\@abovecaptionskip}% + \@float{table}} + {\end@float} + +% footnote formatting +\setlength{\footnotesep }{6.65\p@} +\setlength{\skip\footins}{9\p@ \@plus 4\p@ \@minus 2\p@} +\renewcommand{\footnoterule}{\kern-3\p@ \hrule width 12pc \kern 2.6\p@} +\setcounter{footnote}{0} + +% paragraph formatting +\setlength{\parindent}{\z@} +\setlength{\parskip }{5.5\p@} + +% list formatting +\setlength{\topsep }{4\p@ \@plus 1\p@ \@minus 2\p@} +\setlength{\partopsep }{1\p@ \@plus 0.5\p@ \@minus 0.5\p@} +\setlength{\itemsep }{2\p@ \@plus 1\p@ \@minus 0.5\p@} +\setlength{\parsep }{2\p@ \@plus 1\p@ \@minus 0.5\p@} +\setlength{\leftmargin }{3pc} +\setlength{\leftmargini }{\leftmargin} +\setlength{\leftmarginii }{2em} +\setlength{\leftmarginiii}{1.5em} +\setlength{\leftmarginiv }{1.0em} +\setlength{\leftmarginv }{0.5em} +\def\@listi {\leftmargin\leftmargini} +\def\@listii {\leftmargin\leftmarginii + \labelwidth\leftmarginii + \advance\labelwidth-\labelsep + \topsep 2\p@ \@plus 1\p@ \@minus 0.5\p@ + \parsep 1\p@ \@plus 0.5\p@ \@minus 0.5\p@ + \itemsep \parsep} +\def\@listiii{\leftmargin\leftmarginiii + \labelwidth\leftmarginiii + \advance\labelwidth-\labelsep + \topsep 1\p@ \@plus 0.5\p@ \@minus 0.5\p@ + \parsep \z@ + \partopsep 0.5\p@ \@plus 0\p@ \@minus 0.5\p@ + \itemsep \topsep} +\def\@listiv {\leftmargin\leftmarginiv + \labelwidth\leftmarginiv + \advance\labelwidth-\labelsep} +\def\@listv {\leftmargin\leftmarginv + \labelwidth\leftmarginv + \advance\labelwidth-\labelsep} +\def\@listvi {\leftmargin\leftmarginvi + \labelwidth\leftmarginvi + \advance\labelwidth-\labelsep} + +% create title +\providecommand{\maketitle}{} +\renewcommand{\maketitle}{% + \par + \begingroup + \renewcommand{\thefootnote}{\fnsymbol{footnote}} + % for perfect author name centering + %\renewcommand{\@makefnmark}{\hbox to \z@{$^{\@thefnmark}$\hss}} + % The footnote-mark was overlapping the footnote-text, + % added the following to fix this problem (MK) + \long\def\@makefntext##1{% + \parindent 1em\noindent + \hbox to 1.8em{\hss $\m@th ^{\@thefnmark}$}##1 + } + \thispagestyle{empty} + \@maketitle + \@thanks + %\@notice + \endgroup + \let\maketitle\relax + \let\thanks\relax +} + +% rules for title box at top of first page +\newcommand{\@toptitlebar}{ + \hrule height 2\p@ + \vskip 0.25in + \vskip -\parskip% +} +\newcommand{\@bottomtitlebar}{ + \vskip 0.29in + \vskip -\parskip + \hrule height 2\p@ + \vskip 0.09in% +} + +% create title (includes both anonymized and non-anonymized versions) +\providecommand{\@maketitle}{} +\renewcommand{\@maketitle}{% + \vbox{% + \hsize\textwidth + \linewidth\hsize + \vskip 0.1in + \@toptitlebar + \centering + {\LARGE\sc \@title\par} + \@bottomtitlebar + \textsc{\undertitle}\\ + \vskip 0.1in + \def\And{% + \end{tabular}\hfil\linebreak[0]\hfil% + \begin{tabular}[t]{c}\bf\rule{\z@}{24\p@}\ignorespaces% + } + \def\AND{% + \end{tabular}\hfil\linebreak[4]\hfil% + \begin{tabular}[t]{c}\bf\rule{\z@}{24\p@}\ignorespaces% + } + \begin{tabular}[t]{c}\bf\rule{\z@}{24\p@}\@author\end{tabular}% + \vskip 0.4in \@minus 0.1in \center{\@date} \vskip 0.2in + } +} + +% add conference notice to bottom of first page +\newcommand{\ftype@noticebox}{8} +\newcommand{\@notice}{% + % give a bit of extra room back to authors on first page + \enlargethispage{2\baselineskip}% + \@float{noticebox}[b]% + \footnotesize\@noticestring% + \end@float% +} + +% abstract styling +\renewenvironment{abstract} +{ + \centerline + {\large \bfseries \scshape Abstract} + \begin{quote} +} +{ + \end{quote} +} + +\endinput diff --git a/fixtures/arxiv-template/orcid.pdf b/fixtures/arxiv-template/orcid.pdf new file mode 100644 index 0000000000000000000000000000000000000000..31a2378788a4d3ef0560e3200db6da55a4a777eb GIT binary patch literal 12397 zcmb_?by$>J*EiB3rAWtsC?PNdLw9!xNJz(!Ll3P;x0IB$G}0m6EnU*xNP~d%H+Vef zIq!L%>wCZNx}N)DhCOTjR@{57wf8^2XUgJ|%&aUNn9sU*BQh{K0U&^_ktHTSKTsZG zV+Jz^aKR-iKuHTI4B`L)N5YrLn05P=2bWMh+_Jz-a9yaW}_=yrG z9YWx=w@-OKe1npSn=TV7F?)AFUzRL^Nd*o6nLsjfpr(~KX!g!F-ogF$%T42(i;K-4 z8$Y%$@{<>$n{HTQnZG@a(pJ#X?$+Sk39qA)`23L4w_#9YcwJcS!+_5vUbyhFY->$9 z&gS9OdGD00E@bD>elVoEoQ}nyk!s0frzCr!()Vp&Ylb4ev|^;bSAJQ@SZ$4qO*BX3B(=h6a&;nvZLO&&hVWE#BtGWM+j#YaD_bk#HA&N=d_*+i5Nt$SD;){1W1QZvPJ|qQqGpo?hpBcQXuMSDa|)dk363c&T${>FvBbAk9%1@sHV^u> zg4#lBUlg?CAApt1o@(Xp;WfKRH?nGj)f-|vS9+$jig6-%H}p@BFVzI&-z^hNH$iMn ze%Beky6=tqj=2BN&c%)STg3CPwo!Alg8-Ec%^*Mph>3-vsI4nN8w6Lgg4pgqx|ndK z1H=Xf0N*zjCQt?9XzS!)3~_|FoU((hu_^?n4TLu(94O%mlTwAj8xC&x2N({pgE+t} zAdUc5)?Xrc7Xrm>ZD4SZj)42_Rl$Udey4RG;*V|y0Pphx{7TFb0F<*ZaRg{%-lwgC zsSAL6aDr#V`Zv>i@4pA(4@)sam?6~G>`xcJvsZw?3{Bt~04v)+VsrfE0296wzfl18 zdlUc@ASn1dMee^~zcT#SJ7WTslobH1e*y0;e<$?EF#dfOG5;|BGY%$D)yW8UUkFVF z`9BAlhYbW46#Q#s_uhPsp6#hyxE23NLBNZT!uG_#r=v?} z`{d&GM>|({H^95gTispwm$YS&I!5cWxLn@SoPoh4m59^DyOZ4J8@4y($Bei(`}NdA zAsefQJ06q3p;oEGa{)5XyZx8zakrPL^+XMP7F~Rw3VmJHhJGqh`eYo?e>aN(Fks#s z;)p3flx%r7u0($nl_hBOqds@&O6eWaHt-9TCwph7s>{-B$pNrh`xHOms_Cw_`yI;; zx};WIJLG~xGYiDfml?Mf0S=O25_c#Vc#opk0`%3WRV_EY=L&UUWO-+7$xp0JlR zT#mjRxxP+V9n$;Q?yKFpHH3aGnVB6ewP;J+YERj!kLpZCW`6!M59ypRXz2o((EoP3 ziDn9?Q_yH!%Fi2bCFZy=J zn9yb8z6=yKZ8kk-`aa*x*X6H&HqiWzvnUr8Xuii{?a4C7Z6)~j%Xi!yhv~hYxgiv- zYXgV%358O!f~CoG)8QEFJ(PoHi^K7;6c4Jasb*b4L)uf~$%?`Qjyhy}Snb>S?+gbX z18wDl^Rsl{BIBCBc=TTD)pNUKEoqz5jUytJP!M zWN-}mYR&OjUSVafdl#}VSYOm}b2iOVqo?Hqi9%sP8AF0Z(KHpFR|X^_m|{(Is`^>i zqIM!~39n@oAsn}aAc*>-CS-p!pvUS|3)mBREt^2#QB^tldEK8Xyq%NtCtB-`LX)}g zW3Ug8WJ-)RonyS7M&^66Hq&Ni71=aSqIU;9eE1emB$zo~)rb#Dpvbv=iEOua)I2(s zZVC7S2>Q;~!9zjx(L)^VE~ZQhtzON>(`rzvyu$wRDOMV~;uDHqdV-ZYSeY)5`td9I zu%s+MznDrKttV5pCjeIgB1S@jHO74P?uLw&@9x$~Gud^c$U9g$B|+DOL46Z($N;>} zt3+MeC?Z<9S-H^0+FJT3uy{DTAbOlxt-g7=j3$|(y|Qu1hv%=@JGWL|UmX$8{&>A) z-#&x9|AsJoE<5rC}FX4 ze=^-z^W3H^xNH!g1)q70y~FeCkQbl?vpFAsKE({g94kmwFV@!4xHy%4Uww(`REmYH z&>-grBVvtOo)WOnCZfA?I|gvS6JW~Uhf>$KC8^1D$4dJ=c^ALE**Gv&^pt`r#nk+~ zVT$S_nB@|~1A~uZ-#?p-^v6Wia#2kx#&IM*w)pF+PvN>nzLjiOq_gO%#6NX~D0+sU za9LRvw3zisf0)V`e5`+9A4XYC?L;lwRp_u#L*fydOo{xS(zi##VpM~1p4)P{bxqO7 zYTky_?}s#o9{I$J@raViho=J#M>%XJ95om~;;vujpgJ%)ILM)7)CgBTXlr|@Czj$Ve01V#po-Gz!)DLf!TwUg zc_xcuk7-ioiG~wydEtrWH2R)hi~6FRjnpQ+AbN4(>mOMav{-FtOzb3&6hBfU1~0|! z*Qo)ak4c9=V!vs6XxD9W`k2v~;7x^EQS(TxuwFQeP~M|(3ME{hRA0(TE3MeopZ$E3 z*ER0>$NJGdLK!?hVKkqg8@mT=g@&!8wvVlKb}Di5S@lN$NDq?C3XpO^bDz^8wZSvl zC-tf+qX{{A)x1lD5~uPQ)Yecu%gfs~K`E z$i4f>BSfRMY)jp%IBhZ7j;d^eXD?R}T9u6T5m2o(DKXv~p2f$$)>F*(w70lTJPy%W zR_PfHMH8vn9JHEg#YRIzn*VBDJgcboy9t_8=e#?g*0N|T9`g^!nsMr@sf_ow zwBqnFerbeeDl0e;6Mi!xcl@0NJA*}@cANV`(0-zUN8L7P4A-t!(6q*-{}Q@n*Gh2C z)=?od5z^)UNvo`YJWnC`n|8Gw$|N8eC64aL6EidJK!p_GM2kVM?@v-kT;6F$vv|6% z$;AD%DL$UN6I#(7;r{k$<@KVIDM=_~Vku5MZ7axwitk0DZptObl0I5~l@2a)t)wZD z5+Y+q@eXJx(57enIfqDm4;?+vU(A*09$S#q*4ou*eRUdMf z&;zpA#YfW|B@A(^N9@Dd`qM2V0|pF$B}Nz7MXdvAy`!1v{XULI#s>2ade6eMEP^d4 z9;$ZRg)+$)f9tq7F{;*k!NwnkCmrYNNDSoAdK> z3(cegw&YIAOmXYCMz)==zdwDOAI*evt+~(AF*(wi6n^`r2X`ca?gf`@u}@Ckn+hY1 zpt2!lH;rfmg-4=|cy$ZQh26)M-ZPKwwT4tF-wy_-URO1uMk3TK6gbS1!9rQY>pHiF zZP|_LmeGLR634P#WKL1S`x^y@l$I0&l*rn=lSeffqak@x(B*k|kNAxc8B>o(Q@#Ft zEoAun3h5Zdfy?r1&z0L+5@gAdYlt+Io#tYgK2LvO5<=fEZ&ft3&>md@J@?>rB2^g2 zHSi0Sg(#*JZ`V-(9ka=ky2|>p| zZ5T;eIU#lz#3AISor7{WxA-B_biTKFL$X|FyL_wM_t2e^uajAU=GTfE(N?s2kFzt^*|_nPKqidJGc}6Kbi;G)zE8+X(~@1x zoZDE>$kNS4uZQ5K-Ewiima8;Bm)xk8O9kmi? zm#xIcu$XW!JY0sc%^;jWZ?}c={YHcw%_w{tgjrD)O>j>GGdRGY` z!nVIx%RfBAj6Azeb6cvYT7CwiVD3k#RoOm_l@t&*zPP=B36+j5>JUbNiL zARykMok8DO{h0~E<4S!5tNlY|8A2%KBi|tXb=kBsh05UbNGvg4+%<3SPrCAYBFNq3 zm|hBaGKwVbbxht!_LwR@M+8CfgzaHG-w-5J89Piv36A44ts`-LXyuiAFeYFK0Rh-z z!^A;ysII`(X$ggyO_mc<6-KS<)93Y-WnyWci?hY$vmZf^r+utV*FeZ_u8pPH&*UHA z05lqu`#x}Q6<8^KNNCan3OHtShBlmJkIM@PetA~Z=9Vg}_JUA7zyYFZny!9p8orfJ z-8*t^Nhe;)D4lyS$L}+_mh++lf8jhN78)L3qUrpA3C#G}L@hH-UfH9c^Lgdrp-ljd zousQ6qT`BxXK<|Ug-J}srm;XvTa}MTZQxaKrc38i7mk=n_sbr@RrW=i8%H}&3rO)Q z!0-;CB;f+vECbeJ)Z^YxXs9(jbzAc^s)Do?WlP#^g@|ccb+ncZxo?;AVfZ8T;l3M< zN062RgVf^zfoZN&^dD~1A+t!kuIy+BcogVAw$+%zQXdX*FlT`YQHJMHYNk&oH`T;7 z^hnTDRa*H5xL;NXz=%(LR37w&j&X*lSdEiKmCXsSE5HUIi{WHY|*U3A>s z6BEz&3**;pbm-O-0;!u)Rf`mMFBq1-1#`DWi{)pd4n3va4VG;Of7gjqR7as)8=rmZ z%!e_uFw+$nIiP{E8h!J%b1jwQiT>`s@aK)ss-CmA8=fVaDMIMq$DhUG9)GfWa%0Yy zDoIe}P}((HEh1uL!j6}HMT3(s|I96j$Bu?Xgd~f$)6ns-=BZV}7*%Kw32J-PC2xrZ z8f7^3F#atr^BUATwI7=c|inS&OC)}3g|*^_L>y@?EGZImWU3D1A-Fd zNNKx|DW|f7gT>tWy|+)cF~Xe|KRHdYALc+q@;jXQpYHX+L_=jndf6Di}!FR2C2BN?zR|VRQ(3uxqywwGnmigcX z&XXY9b_t&8CzBhk+nMbaONYI z0(JW{{Dix=iQhjkozCsZPM@sR1#F&k_Ui8GaRtg)2gob6_Tzq4;TkMUMUYo`(2?1R zQ_Jswr~|ygO!qQvWy4T|U@2F%O3u;-hrzJyF`BLx)cprvO9$1p#^Izo!Z0+>piNM= zh$fY$ZpWBm4kYp)YSkY_{x1)WIT} zR~wK8qL*twswJXUJxZaS^PGgC+bx_RR;kQIiP*;UNb`~5LS!^!{s8wCb2d;iLOP{! zLPI(zN-R~$)-c(ttVuvBSxMW>OlIi?1mu7=w&AUND@}a&1m175Stm`8)n>+(C&$p6OjgU}3RU8k{ z&D&QCBCn-w_tYoG?drskT1R{^rsg&D@OMqpb=xUc9ee4^H%x{}`L6?xs18$)kTFr8 zM_jZ8o5?4vA6hBe$$|a!Hj&#Kd+#Os_}2kGk8)rfutOtyp)w?*70;ko{QP?k3557s zoTzkjUrC0?rkd6wsT2qWgEh#!T|U=M<()L8dV5H+ky3ZMxJexhgUXpdaIlgr8Ra7t zM@FP#ZQEmMZG!8j(GW_e&tQw5Gq~9!lRSLQ%S;JlG?R5`n0n?O$)6%nye7-L{Sox4 zsl6sKDo09Jx}?N22@bnjOak6os5g-Onq%I6?97FpDs4 zwXnt;Xh$X?{}MTM6e-8Dlnsnx#P$P+Sr4n~(hjlM>tvoIxvwQ4?dyZ)V7mn2?2#h> zlwIl<7hJI^NK_^QIFyPdT$Gc>%Vmhg6Bt83*UJ3U_Md<4r3ZFUCpuNjH6H{P)#^!S ze_0;zZFq8O0SFRQ4?xK^1e?1+Gdjxq)#FE;qU99FdNf~tixzs)9sb?>MP5UD#s?CG zNDosfqB?2qEiV@41dx>G;7Fyz@!2$~V5oCxhQrWjI)AL8n&w(H7w3fJAKuKwS`FqP z9^tpd91scAsV5y{Nfi%Pwl9%awjXqifz1~a;@52~`XV!)kc=jy^+lp*C=g2V%+!^C zDrhvdMw*pyJi)d*M~Ux0JLKW6U5(arMRa)>|EOqo9)W%1payx-#&>>vI~u#xjxvWY z;X|683{aMmV_>2yaHZ5yzMH=Pxdx(b#rBqwlG+Y}QpFyjYps7B`d}YAV1+EjEUOd~^xQ6PP3a|qlsZLzCL1_alI)XKD(RAaLJOvk!3D!zLTy*j#5PJj zGbE2ES<}po-2BNmUQrWc7s#Bblh)vano8R8H3v)Y_rB<2; zdss+WI@f{de{jk4CLFh>^X6O4&`H)Oupfr}?1;Dg(lt_OVi`7Tu}I-LcGC?ewqf_G z?308#JxMjN9eGT&Tm&)UYQUoY@M+8|=nE4in{l#fSJksm8m^@u&9=7ZisORpUysRg zP^>k++p?Jr`_dD$Cd#K3ZndFOIDffiE}s%eBp$<-8m2%0fwc2TXW6`b@uJR~D)E)i zRW(*TIM+AEPq5Z^$wH_zP_GR00?82bYSO_E3f&M6m>cq7#c;8v54Qan! z>A_ETW+WE5DJ{PNKEi%Cu?)lM?qz#&;b)#7TIOW)yHr4=IWI#xx;VlPHPFob@TW&cIOxTsN>4zHV%_X4X#p83s#qBnLj;s@A0WTjkq@=^~zOtLm;0B#WJ@F12%TUjKH0@ zgviiAlHShAe*g{k?Ic%vft2oRN@vmYqcYz~=qc;dDe~sZD)RMQ=%=k64(5^s=WK1u z@-xC*^3VBWId%9!F{%!wGa`zh7N^$QN*WGqiXRa#!Zkdi7a0BMHfrpGTsahP7zT#(?^+h z!-5h;G4UqfwUyL`LED*bWwqCmFRq{Jpq}s9n;axzlqJ#E&f6UDtxmknO~ttu4v8oF z$ZDZQ^j!2yflhtG%1O$R8+LQG)NSve>w3zy;7*MqS8fq{{_Zm?3D3rfepdmq!0t2G znfmY-OxPK(SKMT|xch{hyZWLr*994rpC;63gbU0m@k9Ft1XtA5({3CPk->hPQdPBS zu6B_Z0B;OaEP;V49eqFcvuf(Zhv$!RZ){50rGnxYlU;w_@&uMB@@t+yMm?J$O7L5M zSh;mTM@gGg%M|s5@H>x9hf+|w*Z5q4e@7YlL6g6nMn$g|_!MJx9A?O6>Fa{+hRAv|mGQ(~pRunz z1=(j5XIwyFzP?{Nstbo-XwN(AFSS!m#R$E^IZ#54uCMW5)QU3jQ{pH;n28^Mz;2)TY(2*%2wvDo(Lj zp6*vjuV?U?zq;qqCv|GraxF@iS|PQmEIg>IArV0@wAoP2kqTw&QHXl{fo!h>g^>Zl zo*?3b2ENhM6=U9Hj9bL0+O|2>bhr?%Ra9v7nws9Kc^zkWY%y6zrG6c*&nv<^79nn~ z7rt%p`AA2{2Aw$l!%FQqFwD1vt>&j}0bOEQByaa#y7B9C&3i9&oAe*{^FAOZGPsm! z9&MXiC9*WIvM5zwO5@GZV9p;AtK`t~EYIl~T>WNw`hs|DW8Lu6A|JQCriy~~NPXy}#tRCK8g?~J@YoQaPjGQn z%zQ*p&bV7+H}TTKHI@gK_6-9j-~}q`CrH=vYu67L=FIwq3CQ1GxGlPrPfQ1Xdrtw< zTu5faQ=vA@_PTodVPmt%vNJ0}t^8%|7~%6G z_QH7QF>_?GEb6=UAoD%#zH#m9b37aU(pmfD>c}{~`s%i=x+V~Xzs-~@qCv?wh-Mw{ zblik;K8kt!L7g%09Pg{<*B;iSm!$fds$14|hHL=_K68&RVJ&2cdM?K3Jlau=K1D1= zjMZ|ypHQY|y+%CFpJo^e2`hNEi9gpN7LEEg$oc~7LA_=OE<-XVk6IZC%L%1`36lnX zvnwy%W#Tt1L+I5`Ni)S(n$pfYN0|qywhRq5V+ij&@(r5+M|;dcwfhy?%y(PXM2lAr zX4#fIyY{(V=Su*roeAf7DK8Z*4G1+-( zrD-FZCaK@9D(G;LMaG)mwbBpiHztqI^#iUw`!+lkP;cMJp{m_o?f7NwpGl$1P~c@W zH#Zz*Sr{xh&7s_8u$)jed_L(jCZt-;sIB!UqF>3adVdo^5ROUCY(Ol@L`y0`@<IdZDTy%`ho*`K5WZW+J&Xa67rSJ}|r%5orR{kz< za%bRd@dtJHKv7}0#{LJb*3+R{rL*A=5yj`q=UpiMwcsCG3$yQ6-udY-vcFC8e1{Qo zpu6v(zGF?JK(gRojZ=eOcyzFM88fb4(t1dswIOT@nIU&{Cf8I?fwbLS0O||Q{2i>;*se0JN6P-Xgilq zU*np#)SIEk0)|NM?niGB_fL`<;!l-aCLnv6VO@BK-Xk8D<3HSv`f|?BlV%nzF11IR zf^1!C4qu=3sgr^HS@2fr%_-wWg$!u1DN*@%(ZbpU5jaqBdyIo{X~VtHP~Q2zLA~=T z8%HA-5n7^0qC7(i_D1U#rc4)my7a(l`^x1}j4v9U-EJBof1LqghOhyRh+Lr`H9^=3V-)ii4*Sad;XlDqZ5yV56qmCdr43;e8>7?Xw4Dls@l(K_IwO_O))yw}= zf?p+4458vyx=cz|P^IM^DcY#L(nqP@1yxkHtgWY=lnl4h!En{6lr}&FS=MXRLzaJ( zC(tviUjR}jb(z;54ajEQh$=rP=%MvSyl~4Jf0|9ja3X!+qD2qS<&A-mSGLFqF8$eqPNDP;G(dOyBiVNdq7mM8!cV-OBRr$_ zZbGm}OMHNQo2Hz+C5^KR4>Ye_oo&;ss)4%<*LyAcA15~SCgx%j;S^#S%-R?l~xv(>DJsbr3UYwp?X;H=v6B?7BjF2-e6bW zUiZBy!M+~4yZ-i7KjnXX-D#v;@5KX~=LrdJOAfBi@2KDQ4Pb~-LJ)i0C+Izm!-w0BFah(1m_lT99mFq9=5xhq_(*Z0@1n4w46hI1gVi0o+X?F*Rs=K0^vAdNqj|rWSASS<%A)I{% zVRkjNV>bQ8Msx%~9E}BN#8l)ZY3>28ysp-E)^Ms7z||UR z2LU=MWqE*cO#g=bo2jjX8oVV0 zMeh3yAOnRu!NT9gPuKjn3vFWjSHgBq4$xmCVqy%0Kq2?JIl^nr3eVWYnAg>U3n2h>9FkHs%T;J=)~SH|}(V(ajSKUIkRpN<6;#Fb_KVg5^fZ~m9j zf2j5^5&VdN7asW60VIeC_%A*GJxBjKb>a7b0G-SInfh-x!ru<{KaU6c|8zPqz)83F zI|(n@{kYMK^WM)Yhyx5_|(s`oC)Ur)&7w{o5ew(5vYD zF^X`Mh!e~l4!SQK!(S{}R|kkGCY)>x#=Jis|9AkL92{T{fGOZl85a-yJ?|fY&2Jei zD;E!(V*Ed3AP^TA&hq_-j0X&-KmS9<&GGLt5G(w`{0EMM^WXh(^T0{V|HN_sTYexm z@IP^IGBxLakp0~s{P?nfLLA_1egII_!X3_|1_OX9wzhDp^ZjiO0Ls{y+5+y24ku#E zhy%3wLE>!iKM5{&agYQnm;=PaEy2YF66fUL Result<(), String> { + let mut args = env::args().skip(1); + let Some(command) = args.next() else { + return Err("usage: texrra serve [input.tex] [port]".into()); + }; + if command != "serve" { + return Err("the only command is `serve`".into()); + } + + let input_path = args + .next() + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("examples/hello.tex")); + let port = args + .next() + .map(|value| value.parse::().map_err(|_| "port must be a number")) + .transpose()? + .unwrap_or(4173); + if args.next().is_some() { + return Err("usage: texrra serve [input.tex] [port]".into()); + } + if !input_path.is_file() { + return Err(format!( + "input file does not exist: {}", + input_path.display() + )); + } + + let projects_root = env::var_os("TEXRRA_PROJECTS_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("projects")); + let store = projects::ProjectStore::new(projects_root.clone())?; + store.seed_from_input(&input_path)?; + let web_root = find_web_root()?; + + let address = format!("127.0.0.1:{port}"); + let server = + Server::http(&address).map_err(|error| format!("could not start server: {error}"))?; + println!("texrra is listening at http://{address}"); + println!("Projects are stored in {}", projects_root.display()); + match &web_root { + Some(path) => println!("Serving the web frontend from {}", path.display()), + None => println!( + "warning: no web frontend found; clone texrra-web and set TEXRRA_WEB_DIR to its directory" + ), + } + + let mut compiler = rust_typeset::CompilerSession::default(); + for request in server.incoming_requests() { + if let Err(error) = handle_request( + request, + &input_path, + &mut compiler, + &store, + web_root.as_deref(), + ) { + eprintln!("request error: {error}"); + } + } + Ok(()) +} + +fn handle_request( + mut request: Request, + input_path: &PathBuf, + compiler: &mut rust_typeset::CompilerSession, + store: &projects::ProjectStore, + web_root: Option<&Path>, +) -> Result<(), String> { + let url = request.url().to_string(); + let path = url.split('?').next().unwrap_or(&url).to_string(); + let method = request.method().clone(); + if let Some(rest) = path.strip_prefix("/api/projects") { + return handle_project_request(request, &method, rest, &url, compiler, store); + } + match (&method, path.as_str()) { + (&Method::Get, "/") => serve_web_path(request, web_root, "/"), + (&Method::Get, "/source") => { + let source = fs::read_to_string(input_path) + .map_err(|error| format!("could not read {}: {error}", input_path.display()))?; + respond(request, 200, "text/plain; charset=utf-8", &source) + } + (&Method::Post, "/compile") => { + let source = match read_and_save(&mut request, input_path) { + Ok(source) => source, + Err(error) => { + return respond(request, 413, "text/plain; charset=utf-8", &error); + } + }; + match compiler.compile(&source, &input_path.display().to_string()) { + Ok(pdf) => respond_pdf(request, pdf), + Err(error) => respond(request, 422, "text/plain; charset=utf-8", &error), + } + } + (&Method::Get, "/fonts.css") => match rust_typeset::preview_font_css() { + Ok(css) => respond_with_cache( + request, + "text/css; charset=utf-8", + css.into_bytes(), + Some("public, max-age=3600"), + ), + Err(error) => respond(request, 500, "text/plain; charset=utf-8", &error), + }, + (&Method::Get, path) if path.starts_with("/fonts/") => { + let name = &path["/fonts/".len()..]; + match rust_typeset::preview_font_file(name) { + Some(bytes) => respond_with_cache( + request, + "font/ttf", + bytes, + Some("public, max-age=31536000, immutable"), + ), + None => respond(request, 404, "text/plain; charset=utf-8", "not found"), + } + } + (&Method::Post, "/preview") => { + let source = match read_and_save(&mut request, input_path) { + Ok(source) => source, + Err(error) => { + return respond( + request, + 413, + "application/json; charset=utf-8", + &rust_typeset::preview_error_json(&error), + ); + } + }; + match compiler.preview_json(&source, &input_path.display().to_string()) { + Ok(json) => respond(request, 200, "application/json; charset=utf-8", &json), + Err(error) => respond( + request, + 422, + "application/json; charset=utf-8", + &rust_typeset::preview_error_json(&error), + ), + } + } + (&Method::Post, "/texrra") => { + let source = match read_and_save(&mut request, input_path) { + Ok(source) => source, + Err(error) => { + return respond(request, 413, "text/plain; charset=utf-8", &error); + } + }; + match compiler.render_html_preview(&source, &input_path.display().to_string()) { + Ok(html) => respond(request, 200, "text/html; charset=utf-8", &html), + Err(error) => respond(request, 422, "text/plain; charset=utf-8", &error), + } + } + (&Method::Get, path) => serve_web_path(request, web_root, path), + _ => respond(request, 404, "text/plain; charset=utf-8", "not found"), + } +} + +fn find_web_root() -> Result, String> { + if let Some(value) = env::var_os("TEXRRA_WEB_DIR") { + let path = PathBuf::from(value); + if !path.join("index.html").is_file() { + return Err(format!( + "TEXRRA_WEB_DIR does not contain index.html: {}", + path.display() + )); + } + return Ok(Some(path)); + } + for candidate in [Path::new("../web"), Path::new("web")] { + if candidate.join("index.html").is_file() { + return Ok(Some(candidate.to_path_buf())); + } + } + Ok(None) +} + +fn serve_web_path(request: Request, web_root: Option<&Path>, path: &str) -> Result<(), String> { + let Some(web_root) = web_root else { + return respond( + request, + 200, + "text/html; charset=utf-8", + "texrra\ +

texrra web frontend not found

\ +

Clone texrra-web next to this checkout, or set\ + TEXRRA_WEB_DIR to its directory, then reload.

", + ); + }; + let mut relative = percent_decode(path.trim_start_matches('/')); + if relative.is_empty() { + relative = "index.html".to_string(); + } + if relative.contains("..") || relative.contains('\\') || relative.starts_with('/') { + return respond(request, 404, "text/plain; charset=utf-8", "not found"); + } + let file = web_root.join(&relative); + if !file.is_file() { + return respond(request, 404, "text/plain; charset=utf-8", "not found"); + } + let canonical_root = web_root + .canonicalize() + .map_err(|error| format!("could not resolve web root: {error}"))?; + let canonical_file = file + .canonicalize() + .map_err(|error| format!("could not resolve {}: {error}", file.display()))?; + if !canonical_file.starts_with(&canonical_root) { + return respond(request, 404, "text/plain; charset=utf-8", "not found"); + } + let body = fs::read(&canonical_file) + .map_err(|error| format!("could not read {}: {error}", canonical_file.display()))?; + respond_with_cache(request, web_content_type(&relative), body, Some("no-cache")) +} + +fn web_content_type(path: &str) -> &'static str { + let extension = path + .rsplit_once('.') + .map(|(_, extension)| extension.to_ascii_lowercase()) + .unwrap_or_default(); + match extension.as_str() { + "html" => "text/html; charset=utf-8", + "css" => "text/css; charset=utf-8", + "js" | "mjs" => "text/javascript; charset=utf-8", + "svg" => "image/svg+xml", + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "gif" => "image/gif", + "webp" => "image/webp", + "ico" => "image/x-icon", + "json" => "application/json; charset=utf-8", + "woff2" => "font/woff2", + "woff" => "font/woff", + "ttf" => "font/ttf", + _ => "application/octet-stream", + } +} + +const MAX_SOURCE_BYTES: usize = 4 * 1024 * 1024; + +fn read_and_save(request: &mut Request, input_path: &Path) -> Result { + let bytes = read_body_bytes(request, MAX_SOURCE_BYTES)?; + let source = String::from_utf8(bytes).map_err(|_| "source is not valid UTF-8".to_string())?; + fs::write(input_path, &source) + .map_err(|error| format!("could not save {}: {error}", input_path.display()))?; + Ok(source) +} + +fn read_body_bytes(request: &mut Request, limit: usize) -> Result, String> { + if request.body_length().is_some_and(|length| length > limit) { + return Err(body_too_large_message(limit)); + } + let mut bytes = Vec::new(); + let mut buffer = [0_u8; 8192]; + let mut total = 0_usize; + let reader = request.as_reader(); + loop { + let read = reader + .read(&mut buffer) + .map_err(|error| format!("could not read request body: {error}"))?; + if read == 0 { + break; + } + total += read; + if total > limit { + return Err(body_too_large_message(limit)); + } + bytes.extend_from_slice(&buffer[..read]); + } + Ok(bytes) +} + +fn body_too_large_message(limit: usize) -> String { + format!("request body is too large (limit {limit} bytes)") +} + +fn respond(request: Request, status: u16, content_type: &str, body: &str) -> Result<(), String> { + let header = Header::from_bytes("Content-Type", content_type) + .map_err(|_| "invalid response header".to_string())?; + let response = Response::from_string(body) + .with_status_code(StatusCode(status)) + .with_header(header); + request + .respond(response) + .map_err(|error| format!("could not send response: {error}")) +} + +fn respond_with_cache( + request: Request, + content_type: &str, + body: Vec, + cache_control: Option<&str>, +) -> Result<(), String> { + let content_type = Header::from_bytes("Content-Type", content_type) + .map_err(|_| "invalid response header".to_string())?; + let cache_header = cache_control + .map(|value| { + Header::from_bytes("Cache-Control", value) + .map_err(|_| "invalid response header".to_string()) + }) + .transpose()?; + let mut response = Response::from_data(body).with_header(content_type); + if let Some(cache_header) = cache_header { + response = response.with_header(cache_header); + } + request + .respond(response) + .map_err(|error| format!("could not send response: {error}")) +} + +fn respond_pdf(request: Request, pdf: Vec) -> Result<(), String> { + let content_type = Header::from_bytes("Content-Type", "application/pdf") + .map_err(|_| "invalid PDF response header".to_string())?; + let disposition = Header::from_bytes("Content-Disposition", "inline; filename=preview.pdf") + .map_err(|_| "invalid PDF response header".to_string())?; + request + .respond( + Response::from_data(pdf) + .with_header(content_type) + .with_header(disposition), + ) + .map_err(|error| format!("could not send PDF response: {error}")) +} + +const MAX_ZIP_BYTES: usize = 32 * 1024 * 1024; +const MAX_UPLOAD_BYTES: usize = 16 * 1024 * 1024; + +fn handle_project_request( + mut request: Request, + method: &Method, + rest: &str, + url: &str, + compiler: &mut rust_typeset::CompilerSession, + store: &projects::ProjectStore, +) -> Result<(), String> { + let segments = rest + .split('/') + .filter(|segment| !segment.is_empty()) + .collect::>(); + match (method, segments.as_slice()) { + (&Method::Get, []) => match projects_json(store) { + Ok(json) => respond_json(request, 200, &json), + Err(error) => respond_api_error(request, 500, &error), + }, + (&Method::Post, []) => { + let name = query_param(url, "name").unwrap_or_else(|| "project".to_string()); + let bytes = match read_body_bytes(&mut request, MAX_ZIP_BYTES) { + Ok(bytes) => bytes, + Err(error) => return respond_api_error(request, 413, &error), + }; + match store.create_from_zip(&name, &bytes) { + Ok(info) => respond_json(request, 201, &project_json(&info)), + Err(error) => respond_api_error(request, 400, &error), + } + } + (&Method::Post, ["new"]) => { + let name = query_param(url, "name").unwrap_or_else(|| "Untitled project".to_string()); + match store.create_empty(&name) { + Ok(info) => respond_json(request, 201, &project_json(&info)), + Err(error) => respond_api_error(request, 500, &error), + } + } + (&Method::Get, [id]) => match store.info(id) { + Ok(info) => respond_json(request, 200, &project_json(&info)), + Err(error) => respond_api_error(request, 404, &error), + }, + (&Method::Delete, [id]) => match store.delete(id) { + Ok(()) => respond_json(request, 200, "{\"deleted\":true}"), + Err(error) => respond_api_error(request, 404, &error), + }, + (&Method::Get, [id, "zip"]) => match store.zip(id) { + Ok(bytes) => { + let name = format!("{id}.zip"); + respond_file(request, "application/zip", bytes, Some(&name)) + } + Err(error) => respond_api_error(request, 404, &error), + }, + (&Method::Get, [id, "raw"]) => { + let Some(path) = query_param(url, "path") else { + return respond_api_error(request, 400, "missing file path"); + }; + match store.read_file(id, &path) { + Ok(bytes) => { + let download = query_param(url, "download").is_some(); + let name = download.then(|| download_name(&path)); + respond_file(request, file_content_type(&path), bytes, name.as_deref()) + } + Err(error) => respond_api_error(request, 404, &error), + } + } + (&Method::Put, [id, "file"]) | (&Method::Post, [id, "files"]) => { + let Some(path) = query_param(url, "path") else { + return respond_api_error(request, 400, "missing file path"); + }; + let bytes = match read_body_bytes(&mut request, MAX_UPLOAD_BYTES) { + Ok(bytes) => bytes, + Err(error) => return respond_api_error(request, 413, &error), + }; + match store.write_file(id, &path, &bytes) { + Ok(()) => respond_json(request, 200, "{\"saved\":true}"), + Err(error) => respond_api_error(request, 400, &error), + } + } + (&Method::Delete, [id, "file"]) => { + let Some(path) = query_param(url, "path") else { + return respond_api_error(request, 400, "missing file path"); + }; + match store.delete_file(id, &path) { + Ok(()) => respond_json(request, 200, "{\"deleted\":true}"), + Err(error) => respond_api_error(request, 404, &error), + } + } + (&Method::Post, [id, "preview"]) => { + let (source, file_name) = match store.main_source(id) { + Ok(source) => source, + Err(error) => return respond_api_error(request, 422, &error), + }; + match compiler.preview_json(&source, &file_name) { + Ok(json) => respond_json(request, 200, &json), + Err(error) => respond( + request, + 422, + "application/json; charset=utf-8", + &rust_typeset::preview_error_json(&error), + ), + } + } + (&Method::Post, [id, "pdf"]) => { + let (source, file_name) = match store.main_source(id) { + Ok(source) => source, + Err(error) => return respond_api_error(request, 422, &error), + }; + match compiler.compile(&source, &file_name) { + Ok(pdf) => respond_pdf(request, pdf), + Err(error) => respond(request, 422, "text/plain; charset=utf-8", &error), + } + } + _ => respond_api_error(request, 404, "not found"), + } +} + +fn projects_json(store: &projects::ProjectStore) -> Result { + let projects = store.list()?; + let mut output = String::from("{\"projects\":["); + for (index, info) in projects.iter().enumerate() { + if index > 0 { + output.push(','); + } + output.push_str(&project_json(info)); + } + output.push_str("]}"); + Ok(output) +} + +fn project_json(info: &projects::ProjectInfo) -> String { + let mut files = String::new(); + for (index, file) in info.files.iter().enumerate() { + if index > 0 { + files.push(','); + } + let _ = write!( + files, + "{{\"path\":{},\"size\":{}}}", + rust_typeset::json_string(&file.path), + file.size + ); + } + format!( + "{{\"id\":{},\"name\":{},\"mainFile\":{},\"createdAt\":{},\"updatedAt\":{},\"files\":[{}]}}", + rust_typeset::json_string(&info.id), + rust_typeset::json_string(&info.name), + rust_typeset::json_string(&info.main_file), + info.created_at, + info.updated_at, + files + ) +} + +fn query_param(url: &str, name: &str) -> Option { + let (_, query) = url.split_once('?')?; + for pair in query.split('&') { + let (key, value) = pair.split_once('=').unwrap_or((pair, "")); + if percent_decode(key) == name { + return Some(percent_decode(value)); + } + } + None +} + +fn percent_decode(value: &str) -> String { + let bytes = value.as_bytes(); + let mut output = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + match bytes[index] { + b'%' if index + 2 < bytes.len() => { + let high = hex_digit(bytes[index + 1]); + let low = hex_digit(bytes[index + 2]); + match (high, low) { + (Some(high), Some(low)) => { + output.push(high * 16 + low); + index += 3; + } + _ => { + output.push(b'%'); + index += 1; + } + } + } + b'+' => { + output.push(b' '); + index += 1; + } + byte => { + output.push(byte); + index += 1; + } + } + } + String::from_utf8_lossy(&output).to_string() +} + +fn hex_digit(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + +fn respond_json(request: Request, status: u16, body: &str) -> Result<(), String> { + respond(request, status, "application/json; charset=utf-8", body) +} + +fn respond_api_error(request: Request, status: u16, message: &str) -> Result<(), String> { + respond( + request, + status, + "application/json; charset=utf-8", + &format!("{{\"error\":{}}}", rust_typeset::json_string(message)), + ) +} + +fn respond_file( + request: Request, + content_type: &str, + body: Vec, + download_name: Option<&str>, +) -> Result<(), String> { + let content_type_header = Header::from_bytes("Content-Type", content_type) + .map_err(|_| "invalid response header".to_string())?; + let mut response = Response::from_data(body) + .with_status_code(StatusCode(200)) + .with_header(content_type_header); + if let Some(name) = download_name { + let disposition = format!("attachment; filename=\"{}\"", ascii_file_name(name)); + let header = Header::from_bytes("Content-Disposition", disposition) + .map_err(|_| "invalid response header".to_string())?; + response = response.with_header(header); + } + request + .respond(response) + .map_err(|error| format!("could not send response: {error}")) +} + +fn file_content_type(path: &str) -> &'static str { + let extension = path + .rsplit_once('.') + .map(|(_, extension)| extension.to_ascii_lowercase()) + .unwrap_or_default(); + match extension.as_str() { + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "gif" => "image/gif", + "bmp" => "image/bmp", + "webp" => "image/webp", + "pdf" => "application/pdf", + "zip" => "application/zip", + "ttf" => "font/ttf", + "otf" => "font/otf", + _ => "text/plain; charset=utf-8", + } +} + +fn download_name(path: &str) -> String { + path.rsplit('/').next().unwrap_or(path).to_string() +} + +fn ascii_file_name(name: &str) -> String { + name.chars() + .map(|character| { + if character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_' | ' ') { + character + } else { + '_' + } + }) + .collect() +} diff --git a/src/projects.rs b/src/projects.rs new file mode 100644 index 0000000..2b7466f --- /dev/null +++ b/src/projects.rs @@ -0,0 +1,764 @@ +use std::{ + fs, + io::{Read, Write}, + path::{Component, Path, PathBuf}, + time::{SystemTime, UNIX_EPOCH}, +}; + +use flate2::{Compression, Crc, read::DeflateDecoder, write::DeflateEncoder}; + +const MAX_PROJECT_FILES: usize = 2000; +const MAX_PROJECT_BYTES: u64 = 64 * 1024 * 1024; +const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; +const ZIP64_MESSAGE: &str = + "ZIP64 archives are not supported; re-create the archive without ZIP64 extensions"; + +pub(super) struct ProjectFile { + pub(super) path: String, + pub(super) size: u64, +} + +pub(super) struct ProjectInfo { + pub(super) id: String, + pub(super) name: String, + pub(super) main_file: String, + pub(super) created_at: u64, + pub(super) updated_at: u64, + pub(super) files: Vec, +} + +struct Meta { + name: String, + main_file: String, + created_at: u64, + updated_at: u64, +} + +pub(super) struct ProjectStore { + root: PathBuf, + meta: PathBuf, +} + +impl ProjectStore { + pub(super) fn new(root: PathBuf) -> Result { + let meta = root.join(".meta"); + fs::create_dir_all(&meta) + .map_err(|error| format!("could not create {}: {error}", meta.display()))?; + Ok(Self { root, meta }) + } + + pub(super) fn is_empty(&self) -> bool { + self.ids().map(|ids| ids.is_empty()).unwrap_or(true) + } + + pub(super) fn list(&self) -> Result, String> { + let mut projects = Vec::new(); + for id in self.ids()? { + if let Ok(info) = self.info(&id) { + projects.push(info); + } + } + projects.sort_by(|left, right| right.updated_at.cmp(&left.updated_at)); + Ok(projects) + } + + pub(super) fn info(&self, id: &str) -> Result { + let dir = self.project_dir(id)?; + if !dir.is_dir() { + return Err(format!("project `{id}` does not exist")); + } + let files = collect_files(&dir)?; + let mut meta = self.load_meta(id).unwrap_or_else(|| Meta { + name: id.to_string(), + main_file: String::new(), + created_at: now_secs(), + updated_at: now_secs(), + }); + meta.main_file = self.resolve_main(id, &dir, &files, &meta.main_file); + Ok(ProjectInfo { + id: id.to_string(), + name: meta.name, + main_file: meta.main_file, + created_at: meta.created_at, + updated_at: meta.updated_at, + files, + }) + } + + pub(super) fn create_empty(&self, name: &str) -> Result { + let name = clean_name(name); + let id = self.unique_id(&slug(&name)); + let dir = self.root.join(&id); + fs::create_dir_all(&dir).map_err(|error| format!("could not create project: {error}"))?; + let source = + "\\documentclass{article}\n\\begin{document}\nHello, world.\n\\end{document}\n"; + fs::write(dir.join("main.tex"), source) + .map_err(|error| format!("could not write main.tex: {error}"))?; + self.save_meta( + &id, + &Meta { + name, + main_file: "main.tex".to_string(), + created_at: now_secs(), + updated_at: now_secs(), + }, + )?; + self.info(&id) + } + + pub(super) fn create_from_zip(&self, name: &str, bytes: &[u8]) -> Result { + let name = clean_name(name); + let entries = read_zip(bytes)?; + if entries.is_empty() { + return Err("the archive does not contain any files".to_string()); + } + let total: u64 = entries.iter().map(|(_, data)| data.len() as u64).sum(); + if total > MAX_PROJECT_BYTES { + return Err(format!( + "the archive expands to {total} bytes, over the {} byte limit", + MAX_PROJECT_BYTES + )); + } + if entries.len() > MAX_PROJECT_FILES { + return Err(format!( + "the archive contains {} files, over the {} file limit", + entries.len(), + MAX_PROJECT_FILES + )); + } + let id = self.unique_id(&slug(&name)); + let dir = self.root.join(&id); + fs::create_dir_all(&dir).map_err(|error| format!("could not create project: {error}"))?; + let mut names = Vec::new(); + for (entry, data) in &entries { + let Some(path) = entry_path(entry) else { + continue; + }; + let target = dir.join(&path); + if let Some(parent) = target.parent() { + fs::create_dir_all(parent) + .map_err(|error| format!("could not create {}: {error}", parent.display()))?; + } + fs::write(&target, data) + .map_err(|error| format!("could not write {}: {error}", target.display()))?; + names.push(entry.clone()); + } + if names.is_empty() { + let _ = fs::remove_dir_all(&dir); + return Err("the archive does not contain any usable files".to_string()); + } + let main_file = detect_main(&dir, &names).unwrap_or_else(|| { + names + .iter() + .find(|name| name.ends_with(".tex")) + .cloned() + .unwrap_or_else(|| "main.tex".to_string()) + }); + self.save_meta( + &id, + &Meta { + name, + main_file, + created_at: now_secs(), + updated_at: now_secs(), + }, + )?; + self.info(&id) + } + + pub(super) fn delete(&self, id: &str) -> Result<(), String> { + let dir = self.project_dir(id)?; + if !dir.is_dir() { + return Err(format!("project `{id}` does not exist")); + } + fs::remove_dir_all(&dir) + .map_err(|error| format!("could not delete project `{id}`: {error}"))?; + let _ = fs::remove_file(self.meta.join(format!("{id}.meta"))); + Ok(()) + } + + pub(super) fn zip(&self, id: &str) -> Result, String> { + let dir = self.project_dir(id)?; + if !dir.is_dir() { + return Err(format!("project `{id}` does not exist")); + } + let info = self.info(id)?; + let mut entries = Vec::new(); + for file in &info.files { + let path = dir.join(Path::new(&file.path)); + if let Ok(data) = fs::read(&path) { + entries.push((file.path.clone(), data)); + } + } + Ok(write_zip(&entries)) + } + + pub(super) fn read_file(&self, id: &str, relative: &str) -> Result, String> { + let path = self.file_path(id, relative)?; + fs::read(&path).map_err(|error| format!("could not read {relative}: {error}")) + } + + pub(super) fn write_file(&self, id: &str, relative: &str, bytes: &[u8]) -> Result<(), String> { + if bytes.len() as u64 > MAX_FILE_BYTES { + return Err(format!( + "file is too large ({} bytes, limit {MAX_FILE_BYTES})", + bytes.len() + )); + } + let path = self.file_path(id, relative)?; + let info = self.info(id)?; + if !info.files.iter().any(|file| file.path == relative) + && info.files.len() >= MAX_PROJECT_FILES + { + return Err(format!( + "project already contains {} files, over the {MAX_PROJECT_FILES} file limit", + info.files.len() + )); + } + if let Some(parent) = path.parent() { + fs::create_dir_all(parent) + .map_err(|error| format!("could not create {}: {error}", parent.display()))?; + } + fs::write(&path, bytes).map_err(|error| format!("could not write {relative}: {error}"))?; + self.touch(id)?; + Ok(()) + } + + pub(super) fn delete_file(&self, id: &str, relative: &str) -> Result<(), String> { + let path = self.file_path(id, relative)?; + if path.is_dir() { + return Err("path is a directory".to_string()); + } + fs::remove_file(&path).map_err(|error| format!("could not delete {relative}: {error}"))?; + let root = self.project_dir(id)?; + let mut parent = path.parent().map(Path::to_path_buf); + while let Some(directory) = parent { + if directory == root || !directory.starts_with(&root) { + break; + } + if fs::remove_dir(&directory).is_err() { + break; + } + parent = directory.parent().map(Path::to_path_buf); + } + self.touch(id)?; + Ok(()) + } + + pub(super) fn main_source(&self, id: &str) -> Result<(String, String), String> { + let info = self.info(id)?; + if info.main_file.is_empty() { + return Err("project does not contain a TeX file".to_string()); + } + let path = self.file_path(id, &info.main_file)?; + let source = fs::read_to_string(&path) + .map_err(|error| format!("could not read {}: {error}", info.main_file))?; + Ok((source, path.display().to_string())) + } + + pub(super) fn seed_from_input(&self, input_path: &Path) -> Result<(), String> { + if !self.is_empty() { + return Ok(()); + } + let Some(parent) = input_path.parent() else { + return Ok(()); + }; + let Some(file_name) = input_path.file_name().and_then(|name| name.to_str()) else { + return Ok(()); + }; + let stem = input_path + .file_stem() + .and_then(|stem| stem.to_str()) + .unwrap_or("project"); + let id = self.unique_id(&slug(stem)); + let dir = self.root.join(&id); + fs::create_dir_all(&dir).map_err(|error| format!("could not create project: {error}"))?; + let entries = match fs::read_dir(parent) { + Ok(entries) => entries, + Err(_) => return Ok(()), + }; + let mut copied = 0; + for entry in entries.flatten() { + let path = entry.path(); + if !path.is_file() { + continue; + } + let Some(name) = path.file_name().and_then(|name| name.to_str()) else { + continue; + }; + if name.starts_with('.') { + continue; + } + let Ok(metadata) = entry.metadata() else { + continue; + }; + if metadata.len() > MAX_FILE_BYTES { + continue; + } + if fs::copy(&path, dir.join(name)).is_ok() { + copied += 1; + } + } + if copied == 0 { + let _ = fs::remove_dir_all(&dir); + return Ok(()); + } + self.save_meta( + &id, + &Meta { + name: stem.to_string(), + main_file: file_name.to_string(), + created_at: now_secs(), + updated_at: now_secs(), + }, + )?; + Ok(()) + } + + pub(super) fn project_dir(&self, id: &str) -> Result { + if !valid_id(id) { + return Err("invalid project id".to_string()); + } + Ok(self.root.join(id)) + } + + pub(super) fn file_path(&self, id: &str, relative: &str) -> Result { + let dir = self.project_dir(id)?; + let relative = relative.trim_start_matches('/'); + if relative.is_empty() { + return Err("missing file path".to_string()); + } + if relative.contains('\\') { + return Err("invalid file path".to_string()); + } + let mut path = dir.clone(); + for component in Path::new(relative).components() { + match component { + Component::Normal(name) => path.push(name), + _ => return Err("invalid file path".to_string()), + } + } + if !path.starts_with(&dir) { + return Err("invalid file path".to_string()); + } + Ok(path) + } + + fn ids(&self) -> Result, String> { + let entries = match fs::read_dir(&self.root) { + Ok(entries) => entries, + Err(error) => return Err(format!("could not read projects: {error}")), + }; + let mut ids = Vec::new(); + for entry in entries.flatten() { + if !entry.path().is_dir() { + continue; + } + let Some(name) = entry.file_name().to_str().map(str::to_string) else { + continue; + }; + if name.starts_with('.') || !valid_id(&name) { + continue; + } + ids.push(name); + } + ids.sort(); + Ok(ids) + } + + fn unique_id(&self, base: &str) -> String { + let mut candidate = base.to_string(); + let mut index = 2; + while self.root.join(&candidate).exists() { + candidate = format!("{base}-{index}"); + index += 1; + } + candidate + } + + fn resolve_main(&self, id: &str, dir: &Path, files: &[ProjectFile], preferred: &str) -> String { + if !preferred.is_empty() + && valid_relative(preferred) + && files.iter().any(|file| file.path == preferred) + { + return preferred.to_string(); + } + let _ = id; + let names = files + .iter() + .map(|file| file.path.clone()) + .collect::>(); + detect_main(dir, &names) + .or_else(|| names.iter().find(|name| name.ends_with(".tex")).cloned()) + .unwrap_or_default() + } + + fn meta_path(&self, id: &str) -> PathBuf { + self.meta.join(format!("{id}.meta")) + } + + fn load_meta(&self, id: &str) -> Option { + let text = fs::read_to_string(self.meta_path(id)).ok()?; + let mut name = String::new(); + let mut main_file = String::new(); + let mut created_at = 0; + let mut updated_at = 0; + for line in text.lines() { + let Some((key, value)) = line.split_once('=') else { + continue; + }; + match key { + "name" => name = value.to_string(), + "main" => main_file = value.to_string(), + "created" => created_at = value.parse().unwrap_or(0), + "updated" => updated_at = value.parse().unwrap_or(0), + _ => {} + } + } + Some(Meta { + name: if name.is_empty() { + id.to_string() + } else { + name + }, + main_file, + created_at, + updated_at, + }) + } + + fn save_meta(&self, id: &str, meta: &Meta) -> Result<(), String> { + let text = format!( + "name={}\nmain={}\ncreated={}\nupdated={}\n", + meta.name.replace(['\n', '\r'], " "), + meta.main_file, + meta.created_at, + meta.updated_at + ); + fs::write(self.meta_path(id), text) + .map_err(|error| format!("could not save project metadata: {error}")) + } + + fn touch(&self, id: &str) -> Result<(), String> { + let mut meta = self.load_meta(id).unwrap_or_else(|| Meta { + name: id.to_string(), + main_file: String::new(), + created_at: now_secs(), + updated_at: now_secs(), + }); + meta.updated_at = now_secs(); + if meta.main_file.is_empty() { + let info = self.info(id)?; + meta.main_file = info.main_file; + } + self.save_meta(id, &meta) + } +} + +fn now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_secs()) + .unwrap_or(0) +} + +fn clean_name(input: &str) -> String { + let cleaned: String = input + .trim() + .chars() + .filter(|character| !character.is_control()) + .take(80) + .collect(); + if cleaned.is_empty() { + "Untitled project".to_string() + } else { + cleaned + } +} + +fn slug(name: &str) -> String { + let mut output = String::new(); + for character in name.chars() { + if character.is_ascii_alphanumeric() { + output.push(character.to_ascii_lowercase()); + } else if character == '-' || character == '_' { + output.push(character); + } else if !output.ends_with('-') { + output.push('-'); + } + } + let trimmed = output.trim_matches('-'); + let truncated: String = trimmed.chars().take(48).collect(); + if truncated.is_empty() { + "project".to_string() + } else { + truncated + } +} + +fn valid_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= 64 + && id.chars().all(|character| { + character.is_ascii_alphanumeric() || character == '-' || character == '_' + }) +} + +fn valid_relative(path: &str) -> bool { + !path.is_empty() + && !path.starts_with('/') + && !path.contains('\\') + && Path::new(path) + .components() + .all(|component| matches!(component, Component::Normal(_))) +} + +fn entry_path(entry: &str) -> Option { + let normalized = entry.replace('\\', "/"); + let trimmed = normalized.trim_start_matches("./"); + let trimmed = trimmed.trim_end_matches('/'); + if !valid_relative(trimmed) { + return None; + } + Some(trimmed.to_string()) +} + +fn detect_main(directory: &Path, names: &[String]) -> Option { + for candidate in ["main.tex", "document.tex", "paper.tex", "article.tex"] { + if let Some(name) = names.iter().find(|name| name.as_str() == candidate) { + return Some(name.clone()); + } + } + let tex_files = names + .iter() + .filter(|name| name.ends_with(".tex")) + .cloned() + .collect::>(); + for name in &tex_files { + if let Ok(text) = fs::read_to_string(directory.join(name)) { + if text.contains("\\documentclass") || text.contains("\\begin{document}") { + return Some(name.clone()); + } + } + } + tex_files.into_iter().next() +} + +fn collect_files(root: &Path) -> Result, String> { + let mut files = Vec::new(); + let mut stack = vec![(root.to_path_buf(), String::new(), 0_usize)]; + while let Some((directory, prefix, depth)) = stack.pop() { + if depth > 12 { + continue; + } + let entries = match fs::read_dir(&directory) { + Ok(entries) => entries, + Err(_) => continue, + }; + for entry in entries.flatten() { + let path = entry.path(); + let Some(name) = entry.file_name().to_str().map(str::to_string) else { + continue; + }; + if name.starts_with('.') { + continue; + } + let relative = if prefix.is_empty() { + name.clone() + } else { + format!("{prefix}/{name}") + }; + let Ok(file_type) = entry.file_type() else { + continue; + }; + if file_type.is_symlink() { + continue; + } + if file_type.is_dir() { + stack.push((path, relative, depth + 1)); + } else if file_type.is_file() { + let size = entry.metadata().map(|metadata| metadata.len()).unwrap_or(0); + files.push(ProjectFile { + path: relative, + size, + }); + } + } + } + files.sort_by(|left, right| left.path.cmp(&right.path)); + Ok(files) +} + +fn find_eocd(bytes: &[u8]) -> Result { + if bytes.len() < 22 { + return Err("not a zip archive".to_string()); + } + let lowest = bytes.len().saturating_sub(22 + 65_535); + let mut index = bytes.len() - 22; + loop { + if bytes[index..index + 4] == [0x50, 0x4b, 0x05, 0x06] { + return Ok(index); + } + if index == lowest { + break; + } + index -= 1; + } + Err("not a zip archive".to_string()) +} + +fn read_zip(bytes: &[u8]) -> Result)>, String> { + let eocd = find_eocd(bytes)?; + let read_u16 = |offset: usize| -> Result { + bytes + .get(offset..offset + 2) + .map(|slice| u16::from_le_bytes([slice[0], slice[1]])) + .ok_or_else(|| "truncated zip archive".to_string()) + }; + let read_u32 = |offset: usize| -> Result { + bytes + .get(offset..offset + 4) + .map(|slice| u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) + .ok_or_else(|| "truncated zip archive".to_string()) + }; + let count = read_u16(eocd + 10)? as usize; + let cd_size = read_u32(eocd + 12)? as usize; + let cd_offset = read_u32(eocd + 16)? as usize; + if count == 0xffff || cd_offset == 0xffff_ffff || cd_size == 0xffff_ffff { + return Err(ZIP64_MESSAGE.to_string()); + } + let mut entries = Vec::new(); + let mut cursor = cd_offset; + for _ in 0..count { + if read_u32(cursor)? != 0x0201_4b50 { + return Err("corrupt zip central directory".to_string()); + } + let flags = read_u16(cursor + 8)?; + let method = read_u16(cursor + 10)?; + let compressed_size = read_u32(cursor + 20)? as usize; + let uncompressed_size = read_u32(cursor + 24)? as usize; + let name_length = read_u16(cursor + 28)? as usize; + let extra_length = read_u16(cursor + 30)? as usize; + let comment_length = read_u16(cursor + 32)? as usize; + let local_offset = read_u32(cursor + 42)? as usize; + let name_bytes = bytes + .get(cursor + 46..cursor + 46 + name_length) + .ok_or_else(|| "truncated zip archive".to_string())?; + let name = String::from_utf8_lossy(name_bytes).to_string(); + cursor += 46 + name_length + extra_length + comment_length; + + if name.ends_with('/') || name.ends_with('\\') { + continue; + } + if flags & 0x0001 != 0 { + return Err("encrypted zip entries are not supported".to_string()); + } + if read_u32(local_offset)? != 0x0403_4b50 { + return Err("corrupt zip local header".to_string()); + } + let local_name_length = read_u16(local_offset + 26)? as usize; + let local_extra_length = read_u16(local_offset + 28)? as usize; + let data_start = local_offset + 30 + local_name_length + local_extra_length; + let data = bytes + .get(data_start..data_start + compressed_size) + .ok_or_else(|| "truncated zip entry data".to_string())?; + let content = match method { + 0 => data.to_vec(), + 8 => { + let mut decoder = DeflateDecoder::new(data); + let mut output = Vec::new(); + decoder + .read_to_end(&mut output) + .map_err(|error| format!("could not inflate `{name}`: {error}"))?; + output + } + other => { + return Err(format!( + "unsupported zip compression method {other} for `{name}`" + )); + } + }; + if content.len() != uncompressed_size { + return Err(format!("zip entry `{name}` has an inconsistent size")); + } + entries.push((name, content)); + } + Ok(entries) +} + +fn write_zip(entries: &[(String, Vec)]) -> Vec { + let mut output = Vec::new(); + let mut directory = Vec::new(); + for (name, data) in entries { + let offset = output.len() as u32; + let crc = crc32(data); + let compressed = deflate(data); + write_u32(&mut output, 0x0403_4b50); + write_u16(&mut output, 20); + write_u16(&mut output, 0); + write_u16(&mut output, 8); + write_u16(&mut output, 0); + write_u16(&mut output, 0x0021); + write_u32(&mut output, crc); + write_u32(&mut output, compressed.len() as u32); + write_u32(&mut output, data.len() as u32); + write_u16(&mut output, name.len() as u16); + write_u16(&mut output, 0); + output.extend_from_slice(name.as_bytes()); + output.extend_from_slice(&compressed); + + write_u32(&mut directory, 0x0201_4b50); + write_u16(&mut directory, 20); + write_u16(&mut directory, 20); + write_u16(&mut directory, 0); + write_u16(&mut directory, 8); + write_u16(&mut directory, 0); + write_u16(&mut directory, 0x0021); + write_u32(&mut directory, crc); + write_u32(&mut directory, compressed.len() as u32); + write_u32(&mut directory, data.len() as u32); + write_u16(&mut directory, name.len() as u16); + write_u16(&mut directory, 0); + write_u16(&mut directory, 0); + write_u16(&mut directory, 0); + write_u16(&mut directory, 0); + write_u32(&mut directory, 0); + write_u32(&mut directory, offset); + directory.extend_from_slice(name.as_bytes()); + } + let directory_offset = output.len() as u32; + output.extend_from_slice(&directory); + write_u32(&mut output, 0x0605_4b50); + write_u16(&mut output, 0); + write_u16(&mut output, 0); + write_u16(&mut output, entries.len() as u16); + write_u16(&mut output, entries.len() as u16); + write_u32(&mut output, directory.len() as u32); + write_u32(&mut output, directory_offset); + write_u16(&mut output, 0); + output +} + +fn crc32(data: &[u8]) -> u32 { + let mut crc = Crc::new(); + crc.update(data); + crc.sum() +} + +fn deflate(data: &[u8]) -> Vec { + let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default()); + encoder + .write_all(data) + .expect("writing to an in-memory deflate encoder cannot fail"); + encoder + .finish() + .expect("finishing an in-memory deflate encoder cannot fail") +} + +fn write_u16(output: &mut Vec, value: u16) { + output.extend_from_slice(&value.to_le_bytes()); +} + +fn write_u32(output: &mut Vec, value: u32) { + output.extend_from_slice(&value.to_le_bytes()); +} diff --git a/src/rust_typeset.rs b/src/rust_typeset.rs new file mode 100644 index 0000000..e6a799a --- /dev/null +++ b/src/rust_typeset.rs @@ -0,0 +1,1356 @@ +use std::{ + cell::RefCell, + collections::{HashMap, VecDeque}, + env, + ffi::OsString, + fmt::Write as _, + fs, + path::{Path, PathBuf}, + rc::Rc, +}; + +use genpdf::fonts; +use texrra_core::math_list::{math_choice_variant, math_style_command}; +use texrra_core::{MathClass, MathListContext, MathStyle, MathStyleCommand, math_expr::is_cjk}; +mod box_font; +mod document; +mod engine; +mod frontend; +mod math_font; +mod math_layout; +mod page_builder; +mod parser; +mod pdf; +mod texlang_adapter; +mod tex_expansion { + pub(super) use super::texlang_adapter::*; +} +mod text_layout; + +use document::{ + Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, MathAccent, MathAlignment, + MathAlignmentBaseline, MathCellStyle, MathDelimiterCharacter, MathDelimiterGlyph, + MathDelimiterSettings, MathExpr, MathFontFamilies, MathFontSelection, MathFontStyle, + MathFractionDelimiters, MathFractionStyle, MathInfixFractionKind, MathLimitMode, + MathLineBreakPenalties, MathMuGlue, MathPhantomKind, MathRowSpacing, MathSpacingSettings, + RuleBox, Run, +}; +use parser::parse_dimension; + +const PDF_POINTS_PER_INCH: f64 = 72.0; + +pub(super) fn log_timing(label: &str, start: std::time::Instant) { + if env::var_os("TEXRRA_TIMING").is_some() { + eprintln!( + "[timing] {label}: {:.2} ms", + start.elapsed().as_secs_f64() * 1000.0 + ); + } +} + +struct CachedCompilation { + input: FrontendInputKey, + lowered: frontend::LoweredDocumentSource, + document: DocumentModel, +} + +#[derive(Clone, PartialEq, Eq)] +struct FrontendInputKey { + source: String, + file_name: String, + style_search_path: Option, + style_lookup_fingerprint: u64, + date: String, +} + +#[derive(Default)] +pub struct CompilerSession { + paragraph_layout_cache: pdf::ParagraphLayoutCache, + page_layout_cache: pdf::PageLayoutCache, + compilation_cache: VecDeque, + expansion_cache: tex_expansion::ExpansionCache, + math_parse_cache: frontend::MathParseCache, + paragraph_parse_cache: parser::ParagraphParseCache, + math_layout_cache: Rc>, + math_font_metrics_cache: Option<(u64, math_font::MathFontMetrics)>, + preview_resources_cache: Option, +} + +impl CompilerSession { + pub fn compile(&mut self, source: &str, file_name: &str) -> Result, String> { + let timing_start = std::time::Instant::now(); + let source_dir = source_directory(file_name); + let model = self.interpret_document(source, file_name)?; + log_timing("interpret", timing_start); + let (_, math_metrics) = self.cached_math_font_metrics(&model)?; + let pdf = pdf::render_pdf( + model, + source_dir, + &mut self.paragraph_layout_cache, + &mut self.page_layout_cache, + math_metrics, + Rc::clone(&self.math_layout_cache), + )?; + log_timing("compile-total", timing_start); + Ok(pdf) + } + + pub fn preview_json(&mut self, source: &str, file_name: &str) -> Result { + let timing_start = std::time::Instant::now(); + let model = self.interpret_document(source, file_name)?; + let (math_metrics_fingerprint, math_metrics) = self.cached_math_font_metrics(&model)?; + let key = pdf::PreviewResourceKey::new(&model, math_metrics_fingerprint)?; + if self + .preview_resources_cache + .as_ref() + .is_none_or(|cached| cached.key() != &key) + { + self.preview_resources_cache = Some(pdf::PreviewResources::new( + &model, + math_metrics, + math_metrics_fingerprint, + Rc::clone(&self.math_layout_cache), + )?); + } + let resources = self + .preview_resources_cache + .as_ref() + .expect("preview resources were just cached"); + let content_width = model.page.width_mm - model.margins.left - model.margins.right; + let content_height = model.page.height_mm - model.margins.top - model.margins.bottom; + let pages = pdf::preview::render_pages( + &model, + source_directory(file_name), + resources, + content_width, + content_height, + &mut self.paragraph_layout_cache, + &mut self.page_layout_cache, + )?; + let duration_ms = timing_start.elapsed().as_secs_f64() * 1000.0; + log_timing("preview", timing_start); + + let mut json = String::new(); + match pages { + Some(pages) => { + let _ = write!( + json, + "{{\"status\":\"ok\",\"durationMs\":{duration_ms:.2},\"pageWidthMm\":{:.2},\"pageHeightMm\":{:.2},\"pages\":[", + model.page.width_mm, model.page.height_mm + ); + for (index, page) in pages.iter().enumerate() { + if index > 0 { + json.push(','); + } + let _ = write!( + json, + "{{\"hash\":\"{:016x}\",\"svg\":{}}}", + page_hash(&page.svg), + json_string(&page.svg) + ); + } + json.push_str("]}"); + } + None => { + let _ = write!( + json, + "{{\"status\":\"fallback\",\"durationMs\":{duration_ms:.2},\"message\":{}}}", + json_string( + "This document uses layout features that the live preview cannot render yet." + ) + ); + } + } + Ok(json) + } + + pub fn render_html_preview(&mut self, source: &str, file_name: &str) -> Result { + let model = self.interpret_document(source, file_name)?; + let math_metrics = if model.blocks.iter().any(block_contains_math) { + Some(self.cached_math_font_metrics(&model)?.1) + } else { + None + }; + render_html_document( + model, + source_directory(file_name), + Rc::clone(&self.math_layout_cache), + math_metrics, + ) + } + + fn cached_math_font_metrics( + &mut self, + model: &DocumentModel, + ) -> Result<(u64, math_font::MathFontMetrics), String> { + let latin_dir = pdf::latin_font_directory()?; + let custom_math_fonts = model.math_font_files(); + let fingerprint = pdf::math_font_metrics_fingerprint(&latin_dir, &custom_math_fonts)?; + if let Some((cached_fingerprint, metrics)) = &self.math_font_metrics_cache + && *cached_fingerprint == fingerprint + { + return Ok((fingerprint, metrics.clone())); + } + + let metrics = pdf::load_math_font_metrics(&latin_dir)? + .with_additional_glyph_fonts(&custom_math_fonts)?; + self.math_font_metrics_cache = Some((fingerprint, metrics.clone())); + Ok((fingerprint, metrics)) + } + + fn interpret_document( + &mut self, + source: &str, + file_name: &str, + ) -> Result { + let input_key = FrontendInputKey { + source: source.to_string(), + file_name: file_name.to_string(), + style_search_path: env::var_os("TEXRRA_STY_DIR"), + style_lookup_fingerprint: frontend::style_lookup_fingerprint(file_name), + date: frontend::date_stamp(), + }; + if let Some(index) = self + .compilation_cache + .iter() + .position(|cached| cached.input == input_key) + { + let valid = { + let cached = &self.compilation_cache[index]; + cached.lowered.cacheable + && frontend::dependencies_unchanged(&cached.lowered.dependencies) + }; + if valid { + let cached = self + .compilation_cache + .remove(index) + .expect("cached compilation index was found"); + let document = cached.document.clone(); + self.compilation_cache.push_back(cached); + return Ok(document); + } + self.compilation_cache.remove(index); + } + + let preprocessed = frontend::preprocess(source, file_name)?; + let expanded = frontend::expand_tex(preprocessed, &mut self.expansion_cache)?; + let lowered = frontend::lower_math(expanded, &mut self.math_parse_cache)?; + let parsed = parser::parse_document(&lowered.source, &mut self.paragraph_parse_cache); + let document = texrra_core::references::resolve(parsed); + if lowered.cacheable && frontend::dependencies_unchanged(&lowered.dependencies) { + const CACHE_CAPACITY: usize = 3; + if self.compilation_cache.len() == CACHE_CAPACITY { + self.compilation_cache.pop_front(); + } + self.compilation_cache.push_back(CachedCompilation { + input: input_key, + lowered, + document: document.clone(), + }); + } + Ok(document) + } +} + +#[derive(Clone)] +struct MathLayoutEnvironment { + cache: Rc>, + font_fingerprint: u64, + line_font_fingerprint: u64, +} + +struct MathPreviewResources { + font_cache: fonts::FontCache, + metrics: math_font::MathFontMetrics, + layout: MathLayoutEnvironment, + monospace_family: Option>, + font_css: String, +} + +fn load_math_preview_resources( + cache: Rc>, + metrics: math_font::MathFontMetrics, + include_monospace: bool, +) -> Result { + let latin_dir = pdf::latin_font_directory()?; + let monospace_dir = include_monospace + .then(pdf::monospace_font_directory) + .transpose()?; + let latin_fonts = fonts::from_files(&latin_dir, "LiberationSerif", None) + .map_err(|error| format!("could not load Latin fonts: {error}"))?; + let font_fingerprint = pdf::math_font_family_fingerprint(&latin_dir, monospace_dir.as_deref())?; + let mut font_cache = fonts::FontCache::new(latin_fonts); + let monospace_family = if let Some(monospace_dir) = &monospace_dir { + let family = fonts::from_files( + monospace_dir, + "LiberationMono", + Some(fonts::Builtin::Courier), + ) + .map_err(|error| format!("could not load monospaced preview fonts: {error}"))?; + Some(font_cache.add_font_family(family)) + } else { + None + }; + cache.borrow_mut().set_monospace_family(monospace_family); + let layout = MathLayoutEnvironment { + cache, + font_fingerprint, + line_font_fingerprint: font_fingerprint, + }; + let mut font_css = String::from( + ".texrra-math { position: relative; text-align: center; overflow: visible; }\ + .texrra-math-svg { display: block; width: 100%; overflow: visible; }\ + .texrra-inline-math-svg { display: inline; overflow: visible; }", + ); + for (weight, style, file_name) in [ + ("400", "normal", "LiberationSerif-Regular.ttf"), + ("700", "normal", "LiberationSerif-Bold.ttf"), + ("400", "italic", "LiberationSerif-Italic.ttf"), + ("700", "italic", "LiberationSerif-BoldItalic.ttf"), + ] { + let path = latin_dir.join(file_name); + let bytes = fs::read(&path).map_err(|error| { + format!( + "could not read preview math font {}: {error}", + path.display() + ) + })?; + font_css.push_str(&format!( + "@font-face{{font-family:'TexrraMath';font-style:{style};font-weight:{weight};src:url(data:font/ttf;base64,{}) format('truetype');}}", + encode_base64(&bytes), + )); + } + if let Some(monospace_dir) = &monospace_dir { + font_css.push_str(".texrra-page code{font-family:'TexrraMono',monospace;}"); + for (weight, style, file_name) in [ + ("400", "normal", "LiberationMono-Regular.ttf"), + ("700", "normal", "LiberationMono-Bold.ttf"), + ("400", "italic", "LiberationMono-Italic.ttf"), + ("700", "italic", "LiberationMono-BoldItalic.ttf"), + ] { + let path = monospace_dir.join(file_name); + let bytes = fs::read(&path).map_err(|error| { + format!( + "could not read preview monospaced font {}: {error}", + path.display() + ) + })?; + font_css.push_str(&format!( + "@font-face{{font-family:'TexrraMono';font-style:{style};font-weight:{weight};src:url(data:font/ttf;base64,{}) format('truetype');}}", + encode_base64(&bytes), + )); + } + } + Ok(MathPreviewResources { + font_cache, + metrics, + layout, + monospace_family, + font_css, + }) +} + +fn render_html_document( + model: DocumentModel, + source_dir: &Path, + math_layout_cache: Rc>, + math_metrics: Option, +) -> Result { + let math_preview = math_metrics + .map(|metrics| { + load_math_preview_resources( + Rc::clone(&math_layout_cache), + metrics, + pdf::document_contains_monospace(&model), + ) + }) + .transpose()?; + let mut html = format!( + "
", + model.margins.top, model.margins.right, model.margins.bottom, model.margins.left + ); + if let Some(math_preview) = &math_preview { + html.push_str(""); + } + + if model.show_title { + html.push_str("
"); + if !model.title.is_empty() { + html.push_str(&format!("

{}

", escape_html(&model.title))); + } + if !model.author.is_empty() { + html.push_str(&format!( + "

{}

", + escape_html(&model.author) + )); + } + if !model.date.is_empty() { + html.push_str(&format!( + "

{}

", + escape_html(&model.date) + )); + } + html.push_str("
"); + } + + for (index, block) in model.blocks.into_iter().enumerate() { + let source_attributes = + source_attributes(model.block_sources.get(index).and_then(Option::as_ref)); + match block { + Block::Paragraph(runs) => { + html.push_str(&format!("")); + html.push_str(&render_html_runs(&runs, math_preview.as_ref(), 11)); + html.push_str("

"); + } + Block::FramedBox { runs, .. } => { + html.push_str(&format!("
")); + html.push_str(&render_html_runs(&runs, math_preview.as_ref(), 11)); + html.push_str("
"); + } + Block::HorizontalRule { .. } => { + html.push_str(&format!("")); + } + Block::Centered { runs } => { + html.push_str(&format!( + "
" + )); + html.push_str(&render_html_runs(&runs, math_preview.as_ref(), 11)); + html.push_str("
"); + } + Block::Heading { level, runs } => { + let level = level.clamp(1, 3); + html.push_str(&format!( + "{}", + render_html_runs( + &runs, + math_preview.as_ref(), + match level { + 1 => 18, + 2 => 15, + _ => 13, + }, + ) + )); + } + Block::List(list) => html.push_str(&render_html_list( + &list, + &source_attributes, + math_preview.as_ref(), + )), + Block::Table { + rows, + caption, + alignments, + rules, + } => { + html.push_str(&format!( + "" + )); + if let Some(caption) = caption { + html.push_str(""); + } + html.push_str(""); + for (row_index, row) in rows.iter().enumerate() { + let rule_class = if rules.contains(&row_index) { + " class=\"rule-before\"" + } else { + "" + }; + html.push_str(&format!("")); + for (column_index, cell) in row.iter().enumerate() { + let alignment = match alignments.get(column_index).copied() { + Some(ColumnAlignment::Center) => "center", + Some(ColumnAlignment::Right) => "right", + _ => "left", + }; + html.push_str(&format!(""); + } + html.push_str(""); + } + if rules.contains(&rows.len()) { + html.push_str(""); + } + html.push_str("
"); + html.push_str(&render_html_runs(&caption, math_preview.as_ref(), 10)); + html.push_str("
")); + html.push_str(&render_html_runs(cell, math_preview.as_ref(), 10)); + html.push_str("
"); + } + Block::Image { + path, + options, + caption, + } => { + let image_path = PathBuf::from(&path); + let image_path = if image_path.is_absolute() { + image_path + } else { + source_dir.join(image_path) + }; + html.push_str(&format!( + "
" + )); + if let (Some(bytes), Some(mime)) = + (fs::read(&image_path).ok(), image_mime_type(&image_path)) + { + let dimensions = image::image_dimensions(&image_path).ok(); + let style = dimensions + .map(|(width, height)| { + let available_width = + model.page.width_mm - model.margins.left - model.margins.right; + let available_height = + model.page.height_mm - model.margins.top - model.margins.bottom; + let (scale_x, scale_y) = pdf::image_scale( + &options, + width, + height, + available_width, + available_height, + ); + let width_mm = f64::from(width) * 25.4 / 300.0 * scale_x; + let height_mm = f64::from(height) * 25.4 / 300.0 * scale_y; + format!(" style=\"width:{width_mm:.2}mm;height:{height_mm:.2}mm\"") + }) + .unwrap_or_default(); + html.push_str(&format!( + "\"{}\"{style}", + encode_base64(&bytes), + escape_html(&path) + )); + } else { + html.push_str(&format!( + "
Image unavailable: {}
", + escape_html(&path) + )); + } + if let Some(caption) = caption { + html.push_str("
"); + html.push_str(&render_html_runs(&caption, math_preview.as_ref(), 10)); + html.push_str("
"); + } + html.push_str("
"); + } + Block::Bibliography(items) => { + html.push_str(&format!( + "

References

    " + )); + for (_key, runs) in items { + html.push_str("
  1. "); + html.push_str(&render_html_runs(&runs, math_preview.as_ref(), 10)); + html.push_str("
  2. "); + } + html.push_str("
"); + } + Block::Math { + expression: value, + equation_numbers, + } => { + html.push_str(&format!("
")); + let math_preview = math_preview + .as_ref() + .expect("math preview resources are loaded for display math"); + html.push_str(&math_layout::display_math_svg( + &value, + &math_preview.font_cache, + &math_preview.metrics, + &math_preview.layout.cache, + math_preview.layout.font_fingerprint, + math_preview.monospace_family, + &equation_numbers, + model.page.width_mm - model.margins.left - model.margins.right, + )); + html.push_str("
"); + } + Block::VerticalKern(width) => { + let points = f64::from(width.0) / 65_536.0; + let height = points.max(0.0); + let margin_top = points.min(0.0); + html.push_str(&format!( + "
" + )); + } + Block::VerticalGlue(glue) => { + let points = f64::from(glue.width.0) / 65_536.0; + let height = points.max(0.0); + let margin_top = points.min(0.0); + html.push_str(&format!( + "
" + )); + } + Block::Penalty(_) => {} + Block::PageBreak => html.push_str(&format!( + "
Page break
" + )), + } + } + + html.push_str("
"); + Ok(html) +} + +fn render_html_list( + list: &ListBlock, + source_attributes: &str, + math_preview: Option<&MathPreviewResources>, +) -> String { + let tag = if list.ordered { "ol" } else { "ul" }; + let mut html = format!("<{tag} class=\"texrra-list\"{source_attributes}>"); + for item in &list.items { + html.push_str("
  • "); + html.push_str(&render_html_runs(&item.runs, math_preview, 11)); + for nested in &item.nested { + html.push_str(&render_html_list(nested, "", math_preview)); + } + html.push_str("
  • "); + } + html.push_str(&format!("")); + html +} + +fn source_attributes(source: Option<&tex_expansion::SourceLocation>) -> String { + let Some(source) = source else { + return String::new(); + }; + let origin = match &source.origin { + tex_expansion::SourceOrigin::File(path) + if path == Path::new("texrra-engine-rust-preamble.tex") => + { + return String::new(); + } + tex_expansion::SourceOrigin::File(path) => path.display().to_string(), + tex_expansion::SourceOrigin::Terminal => "terminal".to_string(), + }; + format!( + " data-tex-source-file=\"{}\" data-tex-source-line=\"{}\" data-tex-source-column=\"{}\"", + escape_html(&origin), + source.line, + source.column.saturating_add(1), + ) +} + +fn block_contains_math(block: &Block) -> bool { + let runs_have_math = |runs: &[Run]| runs.iter().any(|run| run.math.is_some()); + fn list_has_math(list: &ListBlock) -> bool { + list.items.iter().any(|item| { + item.runs.iter().any(|run| run.math.is_some()) || item.nested.iter().any(list_has_math) + }) + } + match block { + Block::Paragraph(runs) | Block::Heading { runs, .. } => runs_have_math(runs), + Block::List(list) => list_has_math(list), + Block::Table { rows, caption, .. } => { + caption.as_deref().is_some_and(runs_have_math) + || rows.iter().flatten().any(|cell| runs_have_math(cell)) + } + Block::Image { caption, .. } => caption.as_deref().is_some_and(runs_have_math), + Block::FramedBox { runs, .. } | Block::Centered { runs } => runs_have_math(runs), + Block::HorizontalRule { .. } => false, + Block::Bibliography(items) => items.iter().any(|(_, runs)| runs_have_math(runs)), + Block::Math { .. } => true, + Block::VerticalKern(_) | Block::VerticalGlue(_) | Block::Penalty(_) | Block::PageBreak => { + false + } + } +} + +fn render_html_runs( + runs: &[Run], + math_preview: Option<&MathPreviewResources>, + font_size: u8, +) -> String { + let mut html = String::new(); + for run in runs { + if let Some(width) = run.kern { + let points = f64::from(width.0) / 65_536.0; + let width = points.max(0.0); + let margin_left = points.min(0.0); + html.push_str(&format!( + "" + )); + } + if let Some(glue) = run.glue { + let points = f64::from(glue.width.0) / 65_536.0; + let width = points.max(0.0); + let margin_left = points.min(0.0); + html.push_str(&format!( + "" + )); + } + if let Some(expression) = &run.math { + if let Some(math_preview) = math_preview { + html.push_str(&math_layout::inline_math_svg( + expression, + &math_preview.font_cache, + &math_preview.metrics, + &math_preview.layout.cache, + math_preview.layout.font_fingerprint, + font_size, + run.bold, + math_preview.monospace_family, + )); + } else { + html.push_str(&escape_html(&run.text)); + } + continue; + } + let mut text = escape_html(&run.text); + if run.monospace { + text = format!("{text}"); + } + if run.italic { + text = format!("{text}"); + } + if run.bold { + text = format!("{text}"); + } + html.push_str(&text); + } + html +} + +fn escape_html(source: &str) -> String { + let mut escaped = String::with_capacity(source.len()); + for character in source.chars() { + match character { + '&' => escaped.push_str("&"), + '<' => escaped.push_str("<"), + '>' => escaped.push_str(">"), + '"' => escaped.push_str("""), + '\'' => escaped.push_str("'"), + _ => escaped.push(character), + } + } + escaped +} + +fn image_mime_type(path: &Path) -> Option<&'static str> { + match path.extension()?.to_str()?.to_ascii_lowercase().as_str() { + "png" => Some("image/png"), + "jpg" | "jpeg" => Some("image/jpeg"), + "bmp" => Some("image/bmp"), + _ => None, + } +} + +fn encode_base64(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut encoded = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let first = chunk[0]; + let second = *chunk.get(1).unwrap_or(&0); + let third = *chunk.get(2).unwrap_or(&0); + encoded.push(ALPHABET[(first >> 2) as usize] as char); + encoded.push(ALPHABET[(((first & 0x03) << 4) | (second >> 4)) as usize] as char); + encoded.push(if chunk.len() > 1 { + ALPHABET[(((second & 0x0f) << 2) | (third >> 6)) as usize] as char + } else { + '=' + }); + encoded.push(if chunk.len() > 2 { + ALPHABET[(third & 0x3f) as usize] as char + } else { + '=' + }); + } + encoded +} + +fn page_hash(svg: &str) -> u64 { + let mut hash = 0xcbf2_9ce4_8422_2325_u64; + for byte in svg.as_bytes() { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + hash +} + +pub fn json_string(value: &str) -> String { + let mut output = String::with_capacity(value.len() + 2); + output.push('"'); + for character in value.chars() { + match character { + '"' => output.push_str("\\\""), + '\\' => output.push_str("\\\\"), + '\n' => output.push_str("\\n"), + '\r' => output.push_str("\\r"), + '\t' => output.push_str("\\t"), + character if (character as u32) < 0x20 => { + let _ = write!(output, "\\u{:04x}", character as u32); + } + character => output.push(character), + } + } + output.push('"'); + output +} + +pub fn preview_error_json(message: &str) -> String { + format!( + "{{\"status\":\"error\",\"message\":{}}}", + json_string(message) + ) +} + +fn preview_font_path(name: &str) -> Option { + let (directory, file_name) = match name { + "serif-regular.ttf" => ( + pdf::latin_font_directory().ok()?, + "LiberationSerif-Regular.ttf", + ), + "serif-bold.ttf" => ( + pdf::latin_font_directory().ok()?, + "LiberationSerif-Bold.ttf", + ), + "serif-italic.ttf" => ( + pdf::latin_font_directory().ok()?, + "LiberationSerif-Italic.ttf", + ), + "serif-bolditalic.ttf" => ( + pdf::latin_font_directory().ok()?, + "LiberationSerif-BoldItalic.ttf", + ), + "mono-regular.ttf" => ( + pdf::monospace_font_directory().ok()?, + "LiberationMono-Regular.ttf", + ), + "mono-bold.ttf" => ( + pdf::monospace_font_directory().ok()?, + "LiberationMono-Bold.ttf", + ), + "mono-italic.ttf" => ( + pdf::monospace_font_directory().ok()?, + "LiberationMono-Italic.ttf", + ), + "mono-bolditalic.ttf" => ( + pdf::monospace_font_directory().ok()?, + "LiberationMono-BoldItalic.ttf", + ), + _ => return None, + }; + let path = directory.join(file_name); + path.is_file().then_some(path) +} + +pub fn preview_font_file(name: &str) -> Option> { + fs::read(preview_font_path(name)?).ok() +} + +pub fn preview_font_css() -> Result { + let mut css = String::new(); + for (family, weight, style, url) in [ + ("TexrraSerif", "400", "normal", "serif-regular.ttf"), + ("TexrraSerif", "700", "normal", "serif-bold.ttf"), + ("TexrraSerif", "400", "italic", "serif-italic.ttf"), + ("TexrraSerif", "700", "italic", "serif-bolditalic.ttf"), + ("TexrraMath", "400", "normal", "serif-regular.ttf"), + ("TexrraMath", "700", "normal", "serif-bold.ttf"), + ("TexrraMath", "400", "italic", "serif-italic.ttf"), + ("TexrraMath", "700", "italic", "serif-bolditalic.ttf"), + ("TexrraMono", "400", "normal", "mono-regular.ttf"), + ("TexrraMono", "700", "normal", "mono-bold.ttf"), + ("TexrraMono", "400", "italic", "mono-italic.ttf"), + ("TexrraMono", "700", "italic", "mono-bolditalic.ttf"), + ] { + if preview_font_path(url).is_some() { + let _ = write!( + css, + "@font-face{{font-family:'{family}';font-style:{style};font-weight:{weight};font-display:swap;src:url('/fonts/{url}') format('truetype');}}" + ); + } + } + css.push_str( + "@font-face{font-family:'TexrraCjk';src:local('Noto Serif CJK SC'),local('Source Han Serif SC'),local('Songti SC'),local('SimSun'),local('Microsoft YaHei'),local('Noto Sans CJK SC');}", + ); + Ok(css) +} + +fn source_directory(file_name: &str) -> &Path { + Path::new(file_name) + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")) +} + +struct BibEntry { + kind: String, + key: String, + fields: HashMap, +} + +impl BibEntry { + fn to_latex(&self) -> String { + let field = |name: &str| self.fields.get(name).map(String::as_str).unwrap_or(""); + let mut parts = Vec::new(); + let author = field("author"); + if !author.is_empty() { + parts.push(format!("{author}.")); + } else if !field("editor").is_empty() { + parts.push(format!("{} (ed.).", field("editor"))); + } + let title = field("title"); + if !title.is_empty() { + if self.kind == "book" || self.kind == "inbook" { + parts.push(format!("\\emph{{{title}}}.")); + } else { + parts.push(format!("{title}.")); + } + } + let publication = if field("journal").is_empty() { + field("booktitle") + } else { + field("journal") + }; + if !publication.is_empty() { + parts.push(format!("\\emph{{{publication}}}")); + } + let volume = field("volume"); + let number = field("number"); + let pages = field("pages"); + let mut details = Vec::new(); + if !volume.is_empty() { + details.push(volume.to_string()); + } + if !number.is_empty() { + details.push(format!("({number})")); + } + if !pages.is_empty() { + details.push(format!("pp. {pages}")); + } + if !details.is_empty() { + parts.push(details.join(", ")); + } + let publisher = field("publisher"); + if !publisher.is_empty() { + parts.push(format!("{publisher}.")); + } + for name in ["institution", "school", "organization", "howpublished"] { + if !field(name).is_empty() { + parts.push(format!("{}.", field(name))); + } + } + if !field("edition").is_empty() { + parts.push(format!("{} ed.", field("edition"))); + } + if !field("address").is_empty() { + parts.push(format!("{}:", field("address"))); + } + if !field("month").is_empty() { + parts.push(field("month").to_string()); + } + let year = field("year"); + if !year.is_empty() { + parts.push(format!("({year}).")); + } + if !field("note").is_empty() { + parts.push(format!("{}.", field("note"))); + } + escape_bib_text(&parts.join(" ")) + } +} + +fn escape_bib_text(source: &str) -> String { + let mut output = String::with_capacity(source.len()); + for character in source.chars() { + match character { + '&' if !output.ends_with('\\') => output.push_str("\\&"), + '%' => output.push('%'), + _ => output.push(character), + } + } + output +} + +fn load_bibliography( + file_names: &str, + source_dir: &Path, + dependencies: &mut Vec, +) -> Result, String> { + let mut sources = String::new(); + let mut seen_keys = std::collections::HashSet::new(); + for file_name in file_names + .split(',') + .map(str::trim) + .filter(|name| !name.is_empty()) + { + let mut path = PathBuf::from(file_name); + if path.extension().is_none() { + path.set_extension("bib"); + } + if !path.is_absolute() { + path = source_dir.join(path); + } + let source = fs::read_to_string(&path) + .map_err(|error| format!("could not read bibliography {}: {error}", path.display()))?; + tex_expansion::SourceDependency::record(dependencies, &path, &source); + sources.push_str(&source); + sources.push('\n'); + } + let mut entries = parse_bib_entries(&sources)?; + for entry in &entries { + if !seen_keys.insert(entry.key.clone()) { + return Err(format!("duplicate BibTeX key `{}`", entry.key)); + } + } + let parent_fields = entries + .iter() + .map(|entry| (entry.key.clone(), entry.fields.clone())) + .collect::>(); + for entry in &mut entries { + if let Some(crossref) = entry.fields.remove("crossref") + && let Some(parent) = parent_fields.get(&crossref) + { + for (name, value) in parent { + entry + .fields + .entry(name.clone()) + .or_insert_with(|| value.clone()); + } + } + } + Ok(entries) +} + +fn parse_bib_entries(source: &str) -> Result, String> { + let mut raw_entries = Vec::new(); + let mut string_macros = HashMap::new(); + let mut cursor = 0; + while let Some(offset) = source[cursor..].find('@') { + cursor += offset + 1; + let type_start = cursor; + while source + .as_bytes() + .get(cursor) + .is_some_and(u8::is_ascii_alphabetic) + { + cursor += 1; + } + if type_start == cursor { + continue; + } + let kind = source[type_start..cursor].to_ascii_lowercase(); + while source + .as_bytes() + .get(cursor) + .is_some_and(|byte| byte.is_ascii_whitespace()) + { + cursor += 1; + } + let Some(open) = source.as_bytes().get(cursor).copied() else { + break; + }; + if !matches!(open, b'{' | b'(') { + continue; + } + let (body, after_entry) = read_bib_entry_body(source, cursor, open) + .ok_or_else(|| format!("unclosed BibTeX entry of type `{kind}`"))?; + cursor = after_entry; + if matches!(kind.as_str(), "comment" | "preamble") { + continue; + } + let mut fields = split_bib_top_level(body, ',').into_iter(); + if kind == "string" { + if let Some((name, value)) = body.split_once('=') { + string_macros.insert(name.trim().to_ascii_lowercase(), value.trim().to_string()); + } + continue; + } + let Some(key) = fields.next().map(|value| value.trim().to_string()) else { + continue; + }; + if key.is_empty() { + continue; + } + let mut parsed_fields = HashMap::new(); + for field in fields { + let Some((name, value)) = field.split_once('=') else { + continue; + }; + let name = name.trim().to_ascii_lowercase(); + if !name.is_empty() { + parsed_fields.insert(name, value.trim().to_string()); + } + } + raw_entries.push((kind, key, parsed_fields)); + } + Ok(raw_entries + .into_iter() + .map(|(kind, key, raw_fields)| BibEntry { + kind, + key, + fields: raw_fields + .into_iter() + .map(|(name, value)| (name, expand_bib_value(&value, &string_macros, 0))) + .collect(), + }) + .collect()) +} + +fn read_bib_entry_body(source: &str, open_index: usize, open: u8) -> Option<(&str, usize)> { + let outer_close = if open == b'{' { b'}' } else { b')' }; + let mut outer_depth = 1usize; + let mut brace_depth = 0usize; + let mut quoted = false; + let mut escaped = false; + let mut cursor = open_index + 1; + while cursor < source.len() { + let character = source[cursor..].chars().next()?; + let width = character.len_utf8(); + if escaped { + escaped = false; + cursor += width; + continue; + } + if character == '\\' { + escaped = true; + cursor += width; + continue; + } + if character == '"' && brace_depth == 0 { + quoted = !quoted; + cursor += width; + continue; + } + if !quoted { + if character == '{' { + brace_depth += 1; + } else if character == '}' && brace_depth > 0 { + brace_depth -= 1; + } else if brace_depth == 0 && open == b'{' && character as u32 == u32::from(outer_close) + { + outer_depth -= 1; + if outer_depth == 0 { + return Some((&source[open_index + 1..cursor], cursor + width)); + } + } else if brace_depth == 0 && open == b'(' && character == '(' { + outer_depth += 1; + } else if brace_depth == 0 && open == b'(' && character == ')' { + outer_depth -= 1; + if outer_depth == 0 { + return Some((&source[open_index + 1..cursor], cursor + width)); + } + } + } + cursor += width; + } + None +} + +fn split_bib_top_level(source: &str, delimiter: char) -> Vec<&str> { + let mut parts = Vec::new(); + let mut start = 0; + let mut brace_depth = 0usize; + let mut quoted = false; + let mut escaped = false; + for (index, character) in source.char_indices() { + if escaped { + escaped = false; + continue; + } + if character == '\\' { + escaped = true; + continue; + } + if character == '"' && brace_depth == 0 { + quoted = !quoted; + continue; + } + if quoted { + continue; + } + match character { + '{' => brace_depth += 1, + '}' => brace_depth = brace_depth.saturating_sub(1), + c if c == delimiter && brace_depth == 0 => { + parts.push(&source[start..index]); + start = index + c.len_utf8(); + } + _ => {} + } + } + parts.push(&source[start..]); + parts +} + +fn expand_bib_value(value: &str, macros: &HashMap, depth: usize) -> String { + if depth > 16 { + return value.to_string(); + } + split_bib_top_level(value, '#') + .into_iter() + .map(str::trim) + .map(|part| { + if let Some((inner, after)) = read_braced_group(part, 0) + && after == part.len() + { + return inner.trim().to_string(); + } + if part.starts_with('"') && part.ends_with('"') && part.len() >= 2 { + return part[1..part.len() - 1].trim().to_string(); + } + if let Some(value) = macros.get(&part.to_ascii_lowercase()) { + return expand_bib_value(value, macros, depth + 1); + } + part.to_string() + }) + .collect::>() + .join("") +} + +fn read_control_sequence(source: &str, start: usize) -> (String, usize) { + let bytes = source.as_bytes(); + if bytes.get(start) != Some(&b'\\') { + return (String::new(), start); + } + let mut end = start + 1; + if end < bytes.len() && (bytes[end].is_ascii_alphabetic() || bytes[end] == b'@') { + while end < bytes.len() && (bytes[end].is_ascii_alphabetic() || bytes[end] == b'@') { + end += 1; + } + } else if end < bytes.len() { + end += source[end..] + .chars() + .next() + .expect("valid UTF-8 boundary") + .len_utf8() + - 1; + } + (source[start..end].to_string(), end) +} + +fn read_braced_group(source: &str, index: usize) -> Option<(&str, usize)> { + read_delimited_group(source, index, b'{', b'}') +} + +fn read_delimited_group(source: &str, index: usize, open: u8, close: u8) -> Option<(&str, usize)> { + let bytes = source.as_bytes(); + if bytes.get(index) != Some(&open) { + return None; + } + let mut depth = 1usize; + let mut cursor = index + 1; + while cursor < bytes.len() { + match bytes[cursor] { + b'\\' => { + cursor += 1; + if cursor < bytes.len() { + let character = source[cursor..].chars().next()?; + cursor += character.len_utf8(); + } + } + b'%' => { + cursor = source[cursor..] + .find('\n') + .map(|offset| cursor + offset + 1) + .unwrap_or(source.len()); + } + byte if byte == open => { + depth += 1; + cursor += 1; + } + byte if byte == close => { + depth -= 1; + if depth == 0 { + return Some((&source[index + 1..cursor], cursor + 1)); + } + cursor += 1; + } + _ => { + let character = source[cursor..].chars().next()?; + cursor += character.len_utf8(); + } + } + } + None +} + +fn prohibits_cjk_line_break(previous: char, current: char) -> bool { + if previous == ' ' || current == ' ' { + return true; + } + let previous_is_opening = matches!( + previous, + '(' | '[' + | '{' + | '〈' + | '《' + | '「' + | '『' + | '【' + | '〔' + | '〖' + | '〘' + | '〚' + | '(' + | '[' + | '{' + | '‘' + | '“' + | '«' + | '‹' + ); + let current_is_nonstarter = matches!( + current, + ')' | ']' + | '}' + | ',' + | '.' + | '!' + | '?' + | ':' + | ';' + | '%' + | '、' + | '。' + | ',' + | '.' + | '・' + | ':' + | ';' + | '!' + | '?' + | '‼' + | '⁇' + | '⁈' + | '⁉' + | '〕' + | '〉' + | '》' + | '」' + | '』' + | '】' + | '〗' + | '〙' + | '〛' + | '〟' + | '’' + | '”' + | '»' + | '›' + | 'ぁ' + | 'ぃ' + | 'ぅ' + | 'ぇ' + | 'ぉ' + | 'っ' + | 'ゃ' + | 'ゅ' + | 'ょ' + | 'ゎ' + | 'ァ' + | 'ィ' + | 'ゥ' + | 'ェ' + | 'ォ' + | 'ッ' + | 'ャ' + | 'ュ' + | 'ョ' + | 'ヮ' + | 'ヵ' + | 'ヶ' + | 'ー' + ); + previous_is_opening || current_is_nonstarter +} diff --git a/src/rust_typeset/box_font.rs b/src/rust_typeset/box_font.rs new file mode 100644 index 0000000..b8f6b96 --- /dev/null +++ b/src/rust_typeset/box_font.rs @@ -0,0 +1,191 @@ +use std::rc::Rc; + +use boxworks::{self, ds}; +use common::{Glue, Scaled, font as box_font}; +use rusttype::{Font as RustFont, Scale as RustScale}; + +pub(super) struct BoxFont { + font: Option>>, + size: u8, +} + +impl BoxFont { + pub(super) fn new(font: Rc>, size: u8) -> Self { + Self { + font: Some(font), + size, + } + } + + pub(super) fn pair_kerning(&self, left: char, right: char) -> Scaled { + let Some(font) = &self.font else { + return Scaled::ZERO; + }; + let scale = RustScale::uniform(glyph_height(font)); + let kerning = font.pair_kerning(scale, font.glyph(left).id(), font.glyph(right).id()) + * f32::from(self.size); + scaled_points(f64::from(kerning)) + } +} + +impl box_font::Format for BoxFont { + fn null() -> Self { + Self { + font: None, + size: 0, + } + } + + fn width(&self, character: char) -> Option { + let font = self.font.as_ref()?; + let glyph_height = glyph_height(font); + let width = font + .glyph(character) + .scaled(RustScale::uniform(glyph_height)) + .h_metrics() + .advance_width + * f32::from(self.size); + Some(scaled_points(f64::from(width))) + } + + fn height(&self, _character: char) -> Option { + let font = self.font.as_ref()?; + let units_per_em = f32::from(font.units_per_em()); + let ascent = font.v_metrics_unscaled().ascent / units_per_em * f32::from(self.size); + Some(scaled_points(f64::from(ascent))) + } + + fn depth(&self, _character: char) -> Option { + let font = self.font.as_ref()?; + let units_per_em = f32::from(font.units_per_em()); + let descent = -font.v_metrics_unscaled().descent / units_per_em * f32::from(self.size); + Some(scaled_points(f64::from(descent.max(0.0)))) + } + + fn default_space(&self) -> Glue { + let width = self.width(' ').unwrap_or_else(|| scaled_points(3.0)); + Glue { + width, + stretch: Scaled(width.0 / 2), + stretch_order: common::GlueOrder::Normal, + shrink: Scaled(width.0 / 3), + shrink_order: common::GlueOrder::Normal, + } + } + + fn extra_space(&self) -> Scaled { + Scaled::ZERO + } +} + +/// Hyphenates words with plain TeX's English patterns. +/// +/// TeX starts a word only at glue boundaries and requires at least two letters +/// before and three after the hyphen. Words are tracked across normal kerns so +/// that font pair kerning does not hide a word from the hyphenator. +pub(super) struct TeXHyphenator { + engine: hyphenate::Hyphenator, + lower_caser: hyphenate::AsciiLowerCaser, +} + +const LEFT_HYPHEN_MIN: usize = 2; +const RIGHT_HYPHEN_MIN: usize = 3; + +impl TeXHyphenator { + pub(super) fn get() -> &'static Self { + static HYPHENATOR: std::sync::OnceLock = std::sync::OnceLock::new(); + HYPHENATOR.get_or_init(|| Self { + engine: hyphenate::Hyphenator::plain_tex_en_us(), + lower_caser: hyphenate::AsciiLowerCaser::default(), + }) + } + + fn collect_word_breaks( + &self, + letters: &[(usize, char, box_font::Id)], + breaks: &mut Vec<(usize, box_font::Id)>, + ) { + if letters.len() < LEFT_HYPHEN_MIN + RIGHT_HYPHEN_MIN { + return; + } + let word = letters + .iter() + .map(|(_, character, _)| *character) + .collect::(); + let count = letters.len(); + for position in self.engine.calculate_indices(&self.lower_caser, &word) { + if position >= LEFT_HYPHEN_MIN && count.saturating_sub(position) >= RIGHT_HYPHEN_MIN { + let (index, _, font) = letters[position]; + breaks.push((index, font)); + } + } + } + + fn hyphenate_list(&self, list: &[ds::Horizontal]) -> Vec { + const INLINE_BOX_START: char = '\u{F1000}'; + const INLINE_BOX_END: char = '\u{F1001}'; + let mut breaks = Vec::new(); + let mut letters = Vec::new(); + let mut protected = false; + for (index, item) in list.iter().enumerate() { + match item { + ds::Horizontal::Char(character) if character.char == INLINE_BOX_START => { + protected = true; + self.collect_word_breaks(&letters, &mut breaks); + letters.clear(); + } + ds::Horizontal::Char(character) if character.char == INLINE_BOX_END => { + protected = false; + self.collect_word_breaks(&letters, &mut breaks); + letters.clear(); + } + ds::Horizontal::Char(character) if character.char.is_ascii_alphabetic() => { + if !protected { + letters.push((index, character.char, character.font)); + } + } + ds::Horizontal::Kern(kern) + if kern.kind == ds::KernKind::Normal && !letters.is_empty() => {} + _ => { + if !protected { + self.collect_word_breaks(&letters, &mut breaks); + } + letters.clear(); + } + } + } + self.collect_word_breaks(&letters, &mut breaks); + if breaks.is_empty() { + return list.to_vec(); + } + + let mut result = Vec::with_capacity(list.len() + breaks.len()); + let mut breaks = breaks.into_iter().peekable(); + for (index, item) in list.iter().enumerate() { + while let Some((_, font)) = breaks.next_if(|(at, _)| *at == index) { + result.push(ds::Horizontal::Discretionary(ds::Discretionary { + pre_break: vec![ds::DiscretionaryElem::Char(ds::Char { char: '-', font })], + post_break: Vec::new(), + replace_count: 0, + })); + } + result.push(item.clone()); + } + result + } +} + +impl boxworks::Hyphenator for TeXHyphenator { + fn hyphenate(&self, list: &mut Vec) { + *list = self.hyphenate_list(list); + } +} + +fn glyph_height(font: &RustFont<'static>) -> f32 { + let metrics = font.v_metrics_unscaled(); + (metrics.ascent - metrics.descent) / f32::from(font.units_per_em()) +} + +pub(super) fn scaled_points(points: f64) -> Scaled { + Scaled((points * 65_536.0).round() as i32) +} diff --git a/src/rust_typeset/document.rs b/src/rust_typeset/document.rs new file mode 100644 index 0000000..0a8342d --- /dev/null +++ b/src/rust_typeset/document.rs @@ -0,0 +1,4 @@ +pub(super) use texrra_core::document::{ + Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, RuleBox, Run, +}; +pub(super) use texrra_core::math_expr::*; diff --git a/src/rust_typeset/engine/arithmetic.rs b/src/rust_typeset/engine/arithmetic.rs new file mode 100644 index 0000000..38e8055 --- /dev/null +++ b/src/rust_typeset/engine/arithmetic.rs @@ -0,0 +1,362 @@ +//! TeX arithmetic assignment primitives backed by engine variables. + +use std::fmt::Display; + +use texlang::command::{self, StaticTag, Tag}; +use texlang::error; +use texlang::traits::*; +use texlang::variable::{SupportedType, TypedVariable}; +use texlang::{parse, token, vm}; + +static ADVANCE_TAG: StaticTag = StaticTag::new(); +static MULTIPLY_TAG: StaticTag = StaticTag::new(); +static DIVIDE_TAG: StaticTag = StaticTag::new(); + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub(crate) enum ArithmeticOperation { + Advance, + Multiply, + Divide, +} + +pub(crate) fn get_advance() -> command::BuiltIn { + get_command::() +} + +pub(crate) fn get_multiply() -> command::BuiltIn { + get_command::() +} + +pub(crate) fn get_divide() -> command::BuiltIn { + get_command::() +} + +pub(crate) fn is_arithmetic_tag(tag: Tag) -> bool { + [Advance::tag(), Multiply::tag(), Divide::tag()].contains(&tag) +} + +pub(crate) fn execute( + operation: ArithmeticOperation, + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + match operation { + ArithmeticOperation::Advance => arithmetic_primitive::(token, input), + ArithmeticOperation::Multiply => arithmetic_primitive::(token, input), + ArithmeticOperation::Divide => arithmetic_primitive::(token, input), + } +} + +fn get_command() -> command::BuiltIn { + command::BuiltIn::new_execution(arithmetic_primitive::) + .with_tag(O::tag()) + .with_doc(O::DOC) +} + +trait ArithmeticNumber: Sized + Default + SupportedType + Copy + Display { + fn scan_rhs( + input: &mut vm::ExecutionInput, + ) -> texlang::prelude::Result; + fn wrapping_add(lhs: Self, rhs: Self) -> Self; + fn checked_mul(lhs: Self, rhs: i32) -> Option; + fn wrapping_mul(lhs: Self, rhs: i32) -> Self; + fn checked_div(lhs: Self, rhs: i32) -> Option; +} + +impl ArithmeticNumber for i32 { + fn scan_rhs( + input: &mut vm::ExecutionInput, + ) -> texlang::prelude::Result { + Self::parse(input) + } + + fn wrapping_add(lhs: Self, rhs: Self) -> Self { + lhs.wrapping_add(rhs) + } + fn checked_mul(lhs: Self, rhs: i32) -> Option { + lhs.checked_mul(rhs) + } + fn wrapping_mul(lhs: Self, rhs: i32) -> Self { + lhs.wrapping_mul(rhs) + } + fn checked_div(lhs: Self, rhs: i32) -> Option { + lhs.checked_div(rhs) + } +} + +impl ArithmeticNumber for common::Scaled { + fn scan_rhs( + input: &mut vm::ExecutionInput, + ) -> texlang::prelude::Result { + Self::parse(input) + } + + fn wrapping_add(lhs: Self, rhs: Self) -> Self { + lhs.wrapping_add(rhs) + } + fn checked_mul(lhs: Self, rhs: i32) -> Option { + lhs.checked_mul(rhs) + } + fn wrapping_mul(lhs: Self, rhs: i32) -> Self { + lhs.wrapping_mul(rhs) + } + fn checked_div(lhs: Self, rhs: i32) -> Option { + lhs.checked_div(rhs) + } +} + +impl ArithmeticNumber for common::Glue { + fn scan_rhs( + input: &mut vm::ExecutionInput, + ) -> texlang::prelude::Result { + Self::parse(input) + } + + fn wrapping_add(lhs: Self, rhs: Self) -> Self { + lhs.wrapping_add(rhs) + } + fn checked_mul(lhs: Self, rhs: i32) -> Option { + lhs.checked_mul(rhs) + } + fn wrapping_mul(lhs: Self, rhs: i32) -> Self { + lhs.wrapping_mul(rhs) + } + fn checked_div(lhs: Self, rhs: i32) -> Option { + lhs.checked_div(rhs) + } +} + +impl ArithmeticNumber for texlang::types::MuGlue { + fn scan_rhs( + input: &mut vm::ExecutionInput, + ) -> texlang::prelude::Result { + Self::parse(input) + } + + fn wrapping_add(lhs: Self, rhs: Self) -> Self { + lhs.wrapping_add(rhs) + } + fn checked_mul(lhs: Self, rhs: i32) -> Option { + lhs.checked_mul(rhs) + } + fn wrapping_mul(lhs: Self, rhs: i32) -> Self { + lhs.wrapping_mul(rhs) + } + fn checked_div(lhs: Self, rhs: i32) -> Option { + lhs.checked_div(rhs) + } +} + +trait Operation { + const DOC: &'static str; + const RHS_IS_SAME_TYPE: bool; + type Error: error::TexError; + + fn tag() -> Tag; + + fn apply( + lhs: N, + rhs_integer: i32, + rhs_number: N, + ) -> Result; + + fn apply_to_variable( + variable: TypedVariable, + input: &mut vm::ExecutionInput, + scope: texcraft_stdext::collections::groupingmap::Scope, + ) -> texlang::prelude::Result<()> { + let lhs = *variable.get(input.state()); + let (rhs_integer, rhs_number) = if Self::RHS_IS_SAME_TYPE { + (0, N::scan_rhs(input)?) + } else { + (i32::parse(input)?, N::default()) + }; + let result = match Self::apply(lhs, rhs_integer, rhs_number) { + Ok(result) => result, + Err(error) => return input.error(error), + }; + variable.set(input, scope, result); + Ok(()) + } +} + +struct Advance; + +impl Operation for Advance { + const DOC: &'static str = "Add a quantity to a variable"; + const RHS_IS_SAME_TYPE: bool = true; + type Error = ArithmeticOverflow; + + fn tag() -> Tag { + ADVANCE_TAG.get() + } + + fn apply(lhs: N, _: i32, rhs_number: N) -> Result { + Ok(N::wrapping_add(lhs, rhs_number)) + } +} + +struct Multiply; + +impl Operation for Multiply { + const DOC: &'static str = "Multiply a variable by an integer"; + const RHS_IS_SAME_TYPE: bool = false; + type Error = ArithmeticOverflow; + + fn tag() -> Tag { + MULTIPLY_TAG.get() + } + + fn apply(lhs: N, rhs_integer: i32, _: N) -> Result { + N::checked_mul(lhs, rhs_integer).ok_or_else(|| ArithmeticOverflow { + operation: "multiplication", + lhs: lhs.to_string(), + rhs: rhs_integer.to_string(), + wrapped_result: N::wrapping_mul(lhs, rhs_integer).to_string(), + }) + } +} + +struct Divide; + +impl Operation for Divide { + const DOC: &'static str = "Divide a variable by an integer"; + const RHS_IS_SAME_TYPE: bool = false; + type Error = DivisionByZero; + + fn tag() -> Tag { + DIVIDE_TAG.get() + } + + fn apply(lhs: N, rhs_integer: i32, _: N) -> Result { + N::checked_div(lhs, rhs_integer).ok_or_else(|| DivisionByZero { + numerator: lhs.to_string(), + }) + } +} + +fn arithmetic_primitive( + _: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + let scope = TexlangState::variable_assignment_scope_hook(input.state_mut()); + let token = input.next_or_err(ArithmeticVariableEndOfInput {})?; + match token.value() { + token::Value::CommandRef(command_ref) => match input + .commands_map() + .get_command(&command_ref) + { + None => input.error( + parse::Error::new("a variable", Some(token), "") + .with_got_override("got an undefined control sequence") + .with_annotation_override("undefined control sequence"), + ), + Some(command::Command::Variable(command)) => { + if !command.is_arithmetic() { + input.error( + parse::Error::new("an arithmetic variable", Some(token), "") + .with_got_override("got a non-arithmetic variable"), + )?; + return Ok(()); + } + let variable = command.clone().resolve(token, input.as_mut())?; + OptionalBy::parse(input)?; + match variable { + texlang::variable::Variable::Int(variable) => { + O::apply_to_variable(variable, input, scope) + } + texlang::variable::Variable::Dimen(variable) => { + O::apply_to_variable(variable, input, scope) + } + texlang::variable::Variable::Glue(variable) => { + O::apply_to_variable(variable, input, scope) + } + texlang::variable::Variable::MuGlue(variable) => { + O::apply_to_variable(variable, input, scope) + } + texlang::variable::Variable::SmallInt(_) + | texlang::variable::Variable::CatCode(_) + | texlang::variable::Variable::TokenList(_) + | texlang::variable::Variable::MathCode(_) + | texlang::variable::Variable::Font(_) => { + unreachable!("only arithmetic commands are considered") + } + } + } + Some(command) => input.error( + parse::Error::new("a variable", Some(token), "") + .with_got_override("got a non-variable command") + .with_annotation_override(format!("control sequence referencing {command}")), + ), + }, + _ => input.error( + parse::Error::new("a variable", Some(token), "") + .with_got_override("got a character token"), + ), + } +} + +#[derive(Debug)] +struct ArithmeticVariableEndOfInput; + +impl error::EndOfInputError for ArithmeticVariableEndOfInput { + fn doing(&self) -> String { + "parsing an arithmetic variable".into() + } +} + +struct OptionalBy; + +impl Parsable for OptionalBy { + fn parse_impl( + input: &mut vm::ExpandedStream, + ) -> texlang::prelude::Result { + parse::parse_keyword(input, "by")?; + Ok(Self) + } +} + +#[derive(Debug)] +struct ArithmeticOverflow { + operation: &'static str, + lhs: String, + rhs: String, + wrapped_result: String, +} + +impl error::TexError for ArithmeticOverflow { + fn kind(&self) -> error::Kind { + error::Kind::FailedPrecondition + } + + fn title(&self) -> String { + format!("overflow in checked {}", self.operation) + } + + fn notes(&self) -> Vec { + vec![ + format!("left hand side evaluated to {}", self.lhs).into(), + format!("right hand side evaluated to {}", self.rhs).into(), + format!("wrapped result would be {}", self.wrapped_result).into(), + ] + } +} + +#[derive(Debug)] +struct DivisionByZero { + numerator: String, +} + +impl error::TexError for DivisionByZero { + fn kind(&self) -> error::Kind { + error::Kind::FailedPrecondition + } + + fn title(&self) -> String { + "division by zero".into() + } + + fn notes(&self) -> Vec { + vec![format!("numerator evaluated to {}", self.numerator).into()] + } +} diff --git a/src/rust_typeset/engine/assignment_scope.rs b/src/rust_typeset/engine/assignment_scope.rs new file mode 100644 index 0000000..ad34eb7 --- /dev/null +++ b/src/rust_typeset/engine/assignment_scope.rs @@ -0,0 +1 @@ +pub(crate) use texrra_core::assignment_scope::AssignmentScopeKind; diff --git a/src/rust_typeset/engine/command.rs b/src/rust_typeset/engine/command.rs new file mode 100644 index 0000000..1e3de57 --- /dev/null +++ b/src/rust_typeset/engine/command.rs @@ -0,0 +1 @@ +pub(crate) use texrra_core::command::{EngineCommandMeaning, NativePrimitive}; diff --git a/src/rust_typeset/engine/dimension.rs b/src/rust_typeset/engine/dimension.rs new file mode 100644 index 0000000..fd0bdbc --- /dev/null +++ b/src/rust_typeset/engine/dimension.rs @@ -0,0 +1,969 @@ +use common::{Scaled, ScaledUnit}; + +use super::{ + glue::{TeXGlue, TeXGlueOrder}, + token::EngineCatCode, +}; +use texrra_core::integer::{self, IntegerScanError, IntegerTokenStream}; + +pub(crate) trait DimensionTokenStream: IntegerTokenStream { + fn scan_internal_dimension( + &mut self, + token: Self::Token, + ) -> Result, Self::Error>; + fn scan_internal_glue(&mut self, token: Self::Token) -> Result, Self::Error>; + fn scan_internal_math_glue( + &mut self, + token: Self::Token, + ) -> Result, Self::Error>; + fn scan_internal_math_dimension( + &mut self, + token: Self::Token, + ) -> Result, Self::Error>; + fn em_width(&self) -> Scaled; + fn ex_height(&self) -> Scaled; + fn magnification_ratio(&self) -> i32; +} + +pub(crate) enum InternalMathDimension { + GlueWidth(Scaled), + Integer(i32), +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum UnitSystem { + Physical, + Math, +} + +#[derive(Debug)] +pub(crate) enum DimensionScanError { + Stream(E), + CompatibilityRequired, + MissingNumber(Option), + IllegalUnit(Option), + InvalidExpression(Option), + TooLarge { token: Option, negative: bool }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ScannedDimension { + pub(crate) value: Scaled, + pub(crate) order: TeXGlueOrder, +} + +pub(crate) use texrra_core::integer::ScannedInteger; + +pub(crate) fn scan_integer( + stream: &mut S, +) -> Result> { + integer::scan_integer(stream).map_err(map_integer_error) +} + +pub(crate) fn scan_integer_with_token( + stream: &mut S, +) -> Result, DimensionScanError> { + integer::scan_integer_with_token(stream).map_err(map_integer_error) +} + +fn map_integer_error(error: IntegerScanError) -> DimensionScanError { + match error { + IntegerScanError::Stream(error) => DimensionScanError::Stream(error), + IntegerScanError::CompatibilityRequired => DimensionScanError::CompatibilityRequired, + IntegerScanError::MissingNumber(token) => DimensionScanError::MissingNumber(token), + IntegerScanError::TooLarge { token, negative } => { + DimensionScanError::TooLarge { token, negative } + } + } +} + +pub(crate) fn scan_dimension( + stream: &mut S, + allow_infinite: bool, +) -> Result> { + scan_dimension_with_units(stream, allow_infinite, UnitSystem::Physical) +} + +fn scan_dimension_with_units( + stream: &mut S, + allow_infinite: bool, + unit_system: UnitSystem, +) -> Result> { + let (negative, first) = scan_signs(stream)?; + scan_dimension_from_first(stream, negative, first, allow_infinite, unit_system) +} + +fn scan_dimension_from_first( + stream: &mut S, + negative: bool, + first: S::Token, + allow_infinite: bool, + unit_system: UnitSystem, +) -> Result> { + if stream.is_command_reference(&first) { + let name = stream.control_sequence_name(&first); + if unit_system == UnitSystem::Math && name.as_deref() == Some("muexpr") { + let glue = scan_glue_expression(stream, false, UnitSystem::Math)?; + let value = if negative { -glue.width } else { glue.width }; + return Ok(ScannedDimension { + value, + order: TeXGlueOrder::Normal, + }); + } + if unit_system == UnitSystem::Physical && name.as_deref() == Some("dimexpr") { + let mut value = scan_dimension_expression(stream, false)?; + if negative { + value = -value; + } + return Ok(ScannedDimension { + value, + order: TeXGlueOrder::Normal, + }); + } + if unit_system == UnitSystem::Physical && name.as_deref() == Some("glueexpr") { + let glue = scan_glue_expression(stream, false, UnitSystem::Physical)?; + let value = if negative { -glue.width } else { glue.width }; + return Ok(ScannedDimension { + value, + order: TeXGlueOrder::Normal, + }); + } + let mut value = if unit_system == UnitSystem::Math { + match stream + .scan_internal_math_dimension(first.clone()) + .map_err(DimensionScanError::Stream)? + { + Some(InternalMathDimension::GlueWidth(value)) => value, + Some(InternalMathDimension::Integer(integer)) => { + consume_optional_space(stream)?; + if !scan_keyword(stream, "mu")? { + return Err(DimensionScanError::IllegalUnit(next_token(stream)?)); + } + consume_optional_space(stream)?; + Scaled::new(integer, Scaled::ZERO, ScaledUnit::Point).map_err(|_| { + DimensionScanError::TooLarge { + token: Some(first.clone()), + negative, + } + })? + } + None => return Err(DimensionScanError::CompatibilityRequired), + } + } else { + match stream + .scan_internal_dimension(first) + .map_err(DimensionScanError::Stream)? + { + Some(value) => value, + None => return Err(DimensionScanError::CompatibilityRequired), + } + }; + if negative { + value = -value; + } + return Ok(ScannedDimension { + value, + order: TeXGlueOrder::Normal, + }); + } + + let (integer_part, fractional_part, first_token) = scan_number(stream, first, negative)?; + + // TeX permits one optional space between the number and its unit. + consume_optional_space(stream)?; + + let mut order = TeXGlueOrder::Normal; + let (unit, true_unit) = if unit_system == UnitSystem::Math { + scan_math_unit(stream, allow_infinite, &mut order)? + } else if allow_infinite { + if scan_keyword(stream, "fil")? { + order = TeXGlueOrder::Fil; + while scan_keyword(stream, "l")? { + order = match order { + TeXGlueOrder::Fil => TeXGlueOrder::Fill, + TeXGlueOrder::Fill => TeXGlueOrder::Filll, + TeXGlueOrder::Filll => { + return Err(DimensionScanError::IllegalUnit(next_token(stream)?)); + } + TeXGlueOrder::Normal => unreachable!(), + }; + } + (DimensionUnit::Infinite, false) + } else { + scan_finite_unit(stream)? + } + } else { + scan_finite_unit(stream)? + }; + + consume_optional_space(stream)?; + + let mut value = match unit { + DimensionUnit::Scaled(unit) => Scaled::new(integer_part, fractional_part, unit), + DimensionUnit::FontMetric(metric) => { + let metric = match metric { + FontMetric::Em => stream.em_width(), + FontMetric::Ex => stream.ex_height(), + }; + let fractional = metric.xn_over_d(fractional_part.0, Scaled::ONE.0); + fractional.and_then(|(fractional, _)| metric.nx_plus_y(integer_part, fractional)) + } + DimensionUnit::Infinite => Scaled::new(integer_part, fractional_part, ScaledUnit::Point), + } + .map_err(|_| DimensionScanError::TooLarge { + token: Some(first_token.clone()), + negative, + })?; + + if true_unit { + let magnification = stream.magnification_ratio(); + if !(1..=32_768).contains(&magnification) { + return Err(DimensionScanError::TooLarge { + token: Some(first_token), + negative, + }); + } + value = value + .xn_over_d(1000, magnification) + .map_err(|_| DimensionScanError::TooLarge { + token: Some(first_token.clone()), + negative, + })? + .0; + } + + if value.0 > Scaled::MAX_DIMEN.0 { + return Err(DimensionScanError::TooLarge { + token: Some(first_token), + negative, + }); + } + if negative { + value = -value; + } + Ok(ScannedDimension { value, order }) +} + +fn scan_dimension_expression( + stream: &mut S, + stop_at_right_parenthesis: bool, +) -> Result> { + let mut value = scan_dimension_term(stream)?; + loop { + let Some(token) = next_non_space_token(stream)? else { + if stop_at_right_parenthesis { + return Err(DimensionScanError::InvalidExpression(None)); + } + return Ok(value); + }; + if let Some((operator, EngineCatCode::Other)) = stream.character(&token) { + match operator { + '+' | '-' => { + let right = scan_dimension_term(stream)?; + let signed_right = if operator == '-' { + -i64::from(right.0) + } else { + i64::from(right.0) + }; + let sum = i64::from(value.0) + signed_right; + value = + checked_dimension_sum(value, right, operator == '-').ok_or_else(|| { + DimensionScanError::TooLarge { + token: Some(token), + negative: sum < 0, + } + })?; + continue; + } + ')' if stop_at_right_parenthesis => { + stream.back_token(token); + return Ok(value); + } + _ => {} + } + } else if stream.control_sequence_name(&token).as_deref() == Some("relax") { + if stop_at_right_parenthesis { + return Err(DimensionScanError::InvalidExpression(Some(token))); + } + return Ok(value); + } + stream.back_token(token); + return Ok(value); + } +} + +fn scan_dimension_term( + stream: &mut S, +) -> Result> { + let mut value = scan_dimension_factor(stream)?; + loop { + let Some(token) = next_non_space_token(stream)? else { + return Ok(value); + }; + let Some((operator, EngineCatCode::Other)) = stream.character(&token) else { + stream.back_token(token); + return Ok(value); + }; + if !matches!(operator, '*' | '/') { + stream.back_token(token); + return Ok(value); + } + let factor = scan_integer(stream)?; + if operator == '*' { + if let Some(next) = next_non_space_token(stream)? { + if matches!(stream.character(&next), Some(('/', EngineCatCode::Other))) { + let denominator = scan_integer(stream)?; + value = checked_dimension_scale(value, factor, denominator) + .ok_or_else(|| DimensionScanError::InvalidExpression(Some(next)))?; + continue; + } + stream.back_token(next); + } + let product = i64::from(value.0) * i64::from(factor); + value = checked_dimension_product(value, factor).ok_or_else(|| { + DimensionScanError::TooLarge { + token: Some(token), + negative: product < 0, + } + })?; + } else { + value = checked_dimension_quotient(value, factor) + .ok_or_else(|| DimensionScanError::InvalidExpression(Some(token)))?; + } + } +} + +fn scan_dimension_factor( + stream: &mut S, +) -> Result> { + let (negative, first) = scan_signs(stream)?; + if matches!(stream.character(&first), Some(('(', EngineCatCode::Other))) { + let mut value = scan_dimension_expression(stream, true)?; + let closing = next_non_space_token(stream)?; + if !closing.as_ref().is_some_and(|token| { + matches!(stream.character(token), Some((')', EngineCatCode::Other))) + }) { + return Err(DimensionScanError::InvalidExpression(closing)); + } + if negative { + value = -value; + } + return Ok(value); + } + Ok(scan_dimension_from_first(stream, negative, first, false, UnitSystem::Physical)?.value) +} + +fn next_non_space_token( + stream: &mut S, +) -> Result, DimensionScanError> { + loop { + let Some(token) = next_token(stream)? else { + return Ok(None); + }; + if !stream.is_space(&token) { + return Ok(Some(token)); + } + } +} + +fn checked_dimension_sum(left: Scaled, right: Scaled, subtract: bool) -> Option { + let right = if subtract { + -i64::from(right.0) + } else { + i64::from(right.0) + }; + let value = i64::from(left.0).checked_add(right)?; + dimension_in_range(value).map(|value| Scaled(value as i32)) +} + +fn checked_dimension_product(value: Scaled, factor: i32) -> Option { + let product = i64::from(value.0).checked_mul(i64::from(factor))?; + dimension_in_range(product).map(|product| Scaled(product as i32)) +} + +fn checked_dimension_quotient(value: Scaled, factor: i32) -> Option { + checked_dimension_scale(value, 1, factor) +} + +fn checked_dimension_scale(value: Scaled, numerator: i32, denominator: i32) -> Option { + if denominator == 0 { + return None; + } + let product = i64::from(value.0).checked_mul(i64::from(numerator))?; + let denominator = i64::from(denominator); + let negative = (product < 0) != (denominator < 0); + let product = product.abs(); + let denominator = denominator.abs(); + // TeX rounds scaled-point division to nearest, with ties away from zero. + let quotient = (product + denominator / 2) / denominator; + dimension_in_range(if negative { -quotient } else { quotient }) + .map(|quotient| Scaled(quotient as i32)) +} + +fn dimension_in_range(value: i64) -> Option { + let limit = i64::from(Scaled::MAX_DIMEN.0); + (-limit..=limit).contains(&value).then_some(value) +} + +pub(crate) fn scan_glue( + stream: &mut S, +) -> Result> { + let (negative, first) = scan_signs(stream)?; + scan_glue_from_first(stream, negative, first, UnitSystem::Physical) +} + +pub(crate) fn scan_math_glue( + stream: &mut S, +) -> Result> { + let (negative, first) = scan_signs(stream)?; + scan_glue_from_first(stream, negative, first, UnitSystem::Math) +} + +fn scan_glue_from_first( + stream: &mut S, + negative: bool, + first: S::Token, + unit_system: UnitSystem, +) -> Result> { + if stream.is_command_reference(&first) { + let name = stream.control_sequence_name(&first); + let mut glue = if unit_system == UnitSystem::Math && name.as_deref() == Some("muexpr") { + scan_glue_expression(stream, false, UnitSystem::Math)? + } else if unit_system == UnitSystem::Physical && name.as_deref() == Some("glueexpr") { + scan_glue_expression(stream, false, UnitSystem::Physical)? + } else if unit_system == UnitSystem::Physical && name.as_deref() == Some("dimexpr") { + let width = + scan_dimension_from_first(stream, false, first, false, UnitSystem::Physical)?.value; + scan_glue_parts(stream, width, UnitSystem::Physical)? + } else if unit_system == UnitSystem::Math { + match stream + .scan_internal_math_glue(first.clone()) + .map_err(DimensionScanError::Stream)? + { + Some(glue) => glue, + None => { + let width = + scan_dimension_from_first(stream, false, first, false, UnitSystem::Math)? + .value; + scan_glue_parts(stream, width, UnitSystem::Math)? + } + } + } else { + match stream + .scan_internal_glue(first.clone()) + .map_err(DimensionScanError::Stream)? + { + Some(glue) => glue, + None => { + let width = scan_dimension_from_first( + stream, + false, + first, + false, + UnitSystem::Physical, + )? + .value; + scan_glue_parts(stream, width, UnitSystem::Physical)? + } + } + }; + if negative { + glue = scale_glue(glue, -1, 1) + .ok_or_else(|| DimensionScanError::InvalidExpression(None))?; + } + return Ok(glue); + } + let width = scan_dimension_from_first(stream, negative, first, false, unit_system)?.value; + scan_glue_parts(stream, width, unit_system) +} + +fn scan_glue_parts( + stream: &mut S, + width: Scaled, + unit_system: UnitSystem, +) -> Result> { + let mut glue = TeXGlue { + width, + ..TeXGlue::default() + }; + if scan_keyword(stream, "plus")? { + let stretch = scan_dimension_with_units(stream, true, unit_system)?; + glue.stretch = stretch.value; + glue.stretch_order = stretch.order; + } + if scan_keyword(stream, "minus")? { + let shrink = scan_dimension_with_units(stream, true, unit_system)?; + glue.shrink = shrink.value; + glue.shrink_order = shrink.order; + } + Ok(glue) +} + +fn scan_glue_expression( + stream: &mut S, + stop_at_right_parenthesis: bool, + unit_system: UnitSystem, +) -> Result> { + let mut glue = scan_glue_term(stream, unit_system)?; + loop { + let Some(token) = next_non_space_token(stream)? else { + if stop_at_right_parenthesis { + return Err(DimensionScanError::InvalidExpression(None)); + } + return Ok(glue); + }; + if let Some((operator, EngineCatCode::Other)) = stream.character(&token) { + match operator { + '+' | '-' => { + let right = scan_glue_term(stream, unit_system)?; + glue = combine_glue(glue, right, operator == '-').ok_or_else(|| { + DimensionScanError::TooLarge { + token: Some(token), + negative: glue.width.0 < 0, + } + })?; + continue; + } + ')' if stop_at_right_parenthesis => { + stream.back_token(token); + return Ok(glue); + } + _ => {} + } + } else if stream.control_sequence_name(&token).as_deref() == Some("relax") { + if stop_at_right_parenthesis { + return Err(DimensionScanError::InvalidExpression(Some(token))); + } + return Ok(glue); + } + stream.back_token(token); + return Ok(glue); + } +} + +fn scan_glue_term( + stream: &mut S, + unit_system: UnitSystem, +) -> Result> { + let mut glue = scan_glue_factor(stream, unit_system)?; + loop { + let Some(token) = next_non_space_token(stream)? else { + return Ok(glue); + }; + let Some((operator, EngineCatCode::Other)) = stream.character(&token) else { + stream.back_token(token); + return Ok(glue); + }; + if !matches!(operator, '*' | '/') { + stream.back_token(token); + return Ok(glue); + } + let factor = scan_integer(stream)?; + if operator == '*' { + if let Some(next) = next_non_space_token(stream)? { + if matches!(stream.character(&next), Some(('/', EngineCatCode::Other))) { + let denominator = scan_integer(stream)?; + glue = scale_glue(glue, factor, denominator) + .ok_or_else(|| DimensionScanError::InvalidExpression(Some(next)))?; + continue; + } + stream.back_token(next); + } + } + glue = if operator == '*' { + scale_glue(glue, factor, 1) + } else { + scale_glue(glue, 1, factor) + } + .ok_or_else(|| DimensionScanError::InvalidExpression(Some(token)))?; + } +} + +fn scan_glue_factor( + stream: &mut S, + unit_system: UnitSystem, +) -> Result> { + let (negative, first) = scan_signs(stream)?; + if matches!(stream.character(&first), Some(('(', EngineCatCode::Other))) { + let mut glue = scan_glue_expression(stream, true, unit_system)?; + let closing = next_non_space_token(stream)?; + if !closing.as_ref().is_some_and(|token| { + matches!(stream.character(token), Some((')', EngineCatCode::Other))) + }) { + return Err(DimensionScanError::InvalidExpression(closing)); + } + if negative { + glue = scale_glue(glue, -1, 1) + .ok_or_else(|| DimensionScanError::InvalidExpression(None))?; + } + return Ok(glue); + } + scan_glue_from_first(stream, negative, first, unit_system) +} + +fn combine_glue(left: TeXGlue, right: TeXGlue, subtract: bool) -> Option { + let width = checked_dimension_sum(left.width, right.width, subtract)?; + let (stretch, stretch_order) = combine_glue_component( + left.stretch, + left.stretch_order, + right.stretch, + right.stretch_order, + subtract, + )?; + let (shrink, shrink_order) = combine_glue_component( + left.shrink, + left.shrink_order, + right.shrink, + right.shrink_order, + subtract, + )?; + Some(TeXGlue { + width, + stretch, + stretch_order: if stretch.is_zero() { + TeXGlueOrder::Normal + } else { + stretch_order + }, + shrink, + shrink_order: if shrink.is_zero() { + TeXGlueOrder::Normal + } else { + shrink_order + }, + }) +} + +fn combine_glue_component( + left: Scaled, + left_order: TeXGlueOrder, + right: Scaled, + right_order: TeXGlueOrder, + subtract: bool, +) -> Option<(Scaled, TeXGlueOrder)> { + if left_order == right_order { + let value = checked_dimension_sum(left, right, subtract)?; + return Some((value, left_order)); + } + // Glue keeps only the nonzero component with the higher infinity order. + if left_order.index() < right_order.index() && !right.is_zero() { + return Some((right, right_order)); + } + Some((left, left_order)) +} + +fn scale_glue(glue: TeXGlue, numerator: i32, denominator: i32) -> Option { + let stretch = checked_dimension_scale(glue.stretch, numerator, denominator)?; + let shrink = checked_dimension_scale(glue.shrink, numerator, denominator)?; + Some(TeXGlue { + width: checked_dimension_scale(glue.width, numerator, denominator)?, + stretch, + stretch_order: if stretch.is_zero() { + TeXGlueOrder::Normal + } else { + glue.stretch_order + }, + shrink, + shrink_order: if shrink.is_zero() { + TeXGlueOrder::Normal + } else { + glue.shrink_order + }, + }) +} + +#[derive(Clone, Copy)] +enum FontMetric { + Em, + Ex, +} + +#[derive(Clone, Copy)] +enum DimensionUnit { + Scaled(ScaledUnit), + FontMetric(FontMetric), + Infinite, +} + +fn scan_finite_unit( + stream: &mut S, +) -> Result<(DimensionUnit, bool), DimensionScanError> { + if scan_keyword(stream, "em")? { + return Ok((DimensionUnit::FontMetric(FontMetric::Em), false)); + } + if scan_keyword(stream, "ex")? { + return Ok((DimensionUnit::FontMetric(FontMetric::Ex), false)); + } + let true_unit = scan_keyword(stream, "true")?; + for (keyword, unit) in [ + ("pt", ScaledUnit::Point), + ("in", ScaledUnit::Inch), + ("pc", ScaledUnit::Pica), + ("cm", ScaledUnit::Centimeter), + ("mm", ScaledUnit::Millimeter), + ("bp", ScaledUnit::BigPoint), + ("dd", ScaledUnit::DidotPoint), + ("cc", ScaledUnit::Cicero), + ("sp", ScaledUnit::ScaledPoint), + ] { + if scan_keyword(stream, keyword)? { + return Ok((DimensionUnit::Scaled(unit), true_unit)); + } + } + if true_unit { + return Err(DimensionScanError::IllegalUnit(next_token(stream)?)); + } + Err(DimensionScanError::IllegalUnit(next_token(stream)?)) +} + +fn scan_math_unit( + stream: &mut S, + allow_infinite: bool, + order: &mut TeXGlueOrder, +) -> Result<(DimensionUnit, bool), DimensionScanError> { + if allow_infinite && scan_keyword(stream, "fil")? { + *order = TeXGlueOrder::Fil; + while scan_keyword(stream, "l")? { + *order = match *order { + TeXGlueOrder::Fil => TeXGlueOrder::Fill, + TeXGlueOrder::Fill => TeXGlueOrder::Filll, + TeXGlueOrder::Filll => { + return Err(DimensionScanError::IllegalUnit(next_token(stream)?)); + } + TeXGlueOrder::Normal => unreachable!(), + }; + } + return Ok((DimensionUnit::Infinite, false)); + } + if scan_keyword(stream, "mu")? { + Ok((DimensionUnit::Scaled(ScaledUnit::Point), false)) + } else { + Err(DimensionScanError::IllegalUnit(next_token(stream)?)) + } +} + +fn scan_signs( + stream: &mut S, +) -> Result<(bool, S::Token), DimensionScanError> { + let mut negative = false; + loop { + let Some(token) = next_token(stream)? else { + return Err(DimensionScanError::MissingNumber(None)); + }; + if stream.is_space(&token) { + continue; + } + if let Some((character, EngineCatCode::Other)) = stream.character(&token) { + match character { + '+' => continue, + '-' => { + negative = !negative; + continue; + } + _ => return Ok((negative, token)), + } + } + return Ok((negative, token)); + } +} + +fn scan_number( + stream: &mut S, + first: S::Token, + negative: bool, +) -> Result<(i32, Scaled, S::Token), DimensionScanError> { + let Some((first_character, EngineCatCode::Other)) = stream.character(&first) else { + if stream.is_command_reference(&first) { + return Err(DimensionScanError::CompatibilityRequired); + } + stream.back_token(first.clone()); + return Err(DimensionScanError::MissingNumber(Some(first))); + }; + + let radix = match first_character { + '\'' => 8, + '"' => 16, + '`' => return Err(DimensionScanError::CompatibilityRequired), + _ => 10, + }; + if radix != 10 { + let integer = scan_radix_integer(stream, first.clone(), radix, negative)?; + return Ok((integer, Scaled::ZERO, first)); + } + + let mut integer = 0_u64; + let mut digit_count = 0_usize; + let mut next = Some(first.clone()); + let mut point = false; + while let Some(token) = next.take() { + match digit(stream, &token) { + Some(digit) => { + integer = integer + .checked_mul(10) + .and_then(|value| value.checked_add(u64::from(digit))) + .ok_or_else(|| DimensionScanError::TooLarge { + token: Some(first.clone()), + negative, + })?; + digit_count += 1; + } + None if matches!( + stream.character(&token), + Some(('.', EngineCatCode::Other) | (',', EngineCatCode::Other)) + ) && !point => + { + point = true; + break; + } + None => { + stream.back_token(token); + break; + } + } + next = next_token(stream)?; + } + + let mut fractional = Scaled::ZERO; + if point { + fractional = scan_fraction(stream)?; + } + if digit_count == 0 && !point { + return Err(DimensionScanError::MissingNumber(Some(first))); + } + if integer > i32::MAX as u64 { + return Err(DimensionScanError::TooLarge { + token: Some(first), + negative, + }); + } + Ok((integer as i32, fractional, first)) +} + +fn scan_radix_integer( + stream: &mut S, + first: S::Token, + radix: u8, + negative: bool, +) -> Result> { + let mut value = 0_u64; + let mut digit_count = 0; + loop { + let Some(token) = next_token(stream)? else { + break; + }; + let digit = match stream.character(&token) { + Some((character, EngineCatCode::Other | EngineCatCode::Letter)) => { + character.to_digit(u32::from(radix)) + } + _ => None, + }; + let Some(digit) = digit else { + stream.back_token(token); + break; + }; + value = value + .checked_mul(u64::from(radix)) + .and_then(|value| value.checked_add(u64::from(digit))) + .ok_or_else(|| DimensionScanError::TooLarge { + token: Some(first.clone()), + negative, + })?; + digit_count += 1; + } + if digit_count == 0 || value > i32::MAX as u64 { + return Err(DimensionScanError::TooLarge { + token: Some(first), + negative, + }); + } + Ok(value as i32) +} + +fn scan_fraction( + stream: &mut S, +) -> Result> { + let mut digits = [0_u8; 17]; + let mut count = 0; + loop { + let Some(token) = next_token(stream)? else { + break; + }; + match digit(stream, &token) { + Some(digit) => { + if count < digits.len() { + digits[count] = digit; + count += 1; + } + } + None if stream.is_command_reference(&token) => { + return Err(DimensionScanError::CompatibilityRequired); + } + None => { + stream.back_token(token); + break; + } + } + } + Ok(Scaled::from_decimal_digits(&digits[..count])) +} + +fn digit(stream: &S, token: &S::Token) -> Option { + match stream.character(token) { + Some((character, EngineCatCode::Other)) => character.to_digit(10).map(|d| d as u8), + _ => None, + } +} + +fn scan_keyword( + stream: &mut S, + keyword: &str, +) -> Result> { + let mut matched = Vec::new(); + for expected in keyword.chars() { + let Some(token) = next_token(stream)? else { + for token in matched.into_iter().rev() { + stream.back_token(token); + } + return Ok(false); + }; + if let Some((character, EngineCatCode::Letter)) = stream.character(&token) { + if character.eq_ignore_ascii_case(&expected) { + matched.push(token); + continue; + } + } + if stream.is_command_reference(&token) { + if stream.control_sequence_name(&token).as_deref() == Some("relax") { + stream.back_token(token); + for token in matched.into_iter().rev() { + stream.back_token(token); + } + return Ok(false); + } + return Err(DimensionScanError::CompatibilityRequired); + } + stream.back_token(token); + for token in matched.into_iter().rev() { + stream.back_token(token); + } + return Ok(false); + } + Ok(true) +} + +fn consume_optional_space( + stream: &mut S, +) -> Result<(), DimensionScanError> { + if let Some(token) = next_token(stream)? { + if !stream.is_space(&token) { + stream.back_token(token); + } + } + Ok(()) +} + +fn next_token( + stream: &mut S, +) -> Result, DimensionScanError> { + stream.next_token().map_err(DimensionScanError::Stream) +} diff --git a/src/rust_typeset/engine/environment.rs b/src/rust_typeset/engine/environment.rs new file mode 100644 index 0000000..d5a4156 --- /dev/null +++ b/src/rust_typeset/engine/environment.rs @@ -0,0 +1 @@ +pub(crate) use texrra_core::environment::EnvironmentStack; diff --git a/src/rust_typeset/engine/expansion.rs b/src/rust_typeset/engine/expansion.rs new file mode 100644 index 0000000..8713939 --- /dev/null +++ b/src/rust_typeset/engine/expansion.rs @@ -0,0 +1 @@ +pub(crate) use texrra_core::expansion::*; diff --git a/src/rust_typeset/engine/glue.rs b/src/rust_typeset/engine/glue.rs new file mode 100644 index 0000000..159a786 --- /dev/null +++ b/src/rust_typeset/engine/glue.rs @@ -0,0 +1 @@ +pub(crate) use texrra_core::glue::{TeXGlue, TeXGlueOrder}; diff --git a/src/rust_typeset/engine/input.rs b/src/rust_typeset/engine/input.rs new file mode 100644 index 0000000..dca1a89 --- /dev/null +++ b/src/rust_typeset/engine/input.rs @@ -0,0 +1,3 @@ +pub(crate) use texrra_core::input::{ + FileNameTokenStream, InputFrame, InputId, InputStack, scan_file_location, +}; diff --git a/src/rust_typeset/engine/layout_primitive.rs b/src/rust_typeset/engine/layout_primitive.rs new file mode 100644 index 0000000..5040d9b --- /dev/null +++ b/src/rust_typeset/engine/layout_primitive.rs @@ -0,0 +1,3 @@ +pub(crate) use texrra_core::layout_primitive::{ + LayoutEffect, LayoutPrimitive, LayoutPrimitiveInput, execute, +}; diff --git a/src/rust_typeset/engine/macros.rs b/src/rust_typeset/engine/macros.rs new file mode 100644 index 0000000..9b8c905 --- /dev/null +++ b/src/rust_typeset/engine/macros.rs @@ -0,0 +1 @@ +pub(crate) use texrra_core::macros::*; diff --git a/src/rust_typeset/engine/math_code.rs b/src/rust_typeset/engine/math_code.rs new file mode 100644 index 0000000..e3857ca --- /dev/null +++ b/src/rust_typeset/engine/math_code.rs @@ -0,0 +1 @@ +pub(crate) use texrra_core::math_code::{MathCodeTable, UnicodeMathCode}; diff --git a/src/rust_typeset/engine/mod.rs b/src/rust_typeset/engine/mod.rs new file mode 100644 index 0000000..8d022ba --- /dev/null +++ b/src/rust_typeset/engine/mod.rs @@ -0,0 +1,18 @@ +pub(super) mod arithmetic; +pub(super) mod assignment_scope; +pub(super) mod command; +pub(super) mod dimension; +pub(super) mod environment; +pub(super) mod expansion; +pub(super) mod glue; +pub(super) mod input; +pub(super) mod layout_primitive; +pub(super) mod macros; +pub(super) mod math_code; +pub(super) mod mouth; +pub(super) mod prefix; +pub(super) mod registers; +pub(super) mod state; +pub(super) mod texlang_dimension_adapter; +pub(super) mod token; +pub(super) mod variable; diff --git a/src/rust_typeset/engine/mouth.rs b/src/rust_typeset/engine/mouth.rs new file mode 100644 index 0000000..ef9c8e0 --- /dev/null +++ b/src/rust_typeset/engine/mouth.rs @@ -0,0 +1 @@ +pub(crate) use texrra_core::mouth::{CatCodeTable, Mouth, Token}; diff --git a/src/rust_typeset/engine/prefix.rs b/src/rust_typeset/engine/prefix.rs new file mode 100644 index 0000000..d6505b8 --- /dev/null +++ b/src/rust_typeset/engine/prefix.rs @@ -0,0 +1,176 @@ +use texlang::{ + command::{Command, StaticTag, Tag}, + error, + token::{self, Token}, + traits::TexlangState, + vm::{self, TokenStream}, +}; + +static GLOBAL_TAG: StaticTag = StaticTag::new(); +static LONG_TAG: StaticTag = StaticTag::new(); +static OUTER_TAG: StaticTag = StaticTag::new(); +static RELAX_TAG: StaticTag = StaticTag::new(); +static GLOBAL_ASSIGNMENT_TAG: StaticTag = StaticTag::new(); + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub(crate) enum PrefixKind { + Global, + Long, + Outer, +} + +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct PrefixFlags { + pub(crate) global: bool, + pub(crate) long: bool, + pub(crate) outer: bool, +} + +#[derive(Default)] +struct Prefixes { + global: Option, + long: Option, + outer: Option, +} + +impl Prefixes { + fn add(&mut self, kind: PrefixKind, token: Token) { + let slot = match kind { + PrefixKind::Global => &mut self.global, + PrefixKind::Long => &mut self.long, + PrefixKind::Outer => &mut self.outer, + }; + slot.get_or_insert(token); + } + + fn first_token(&self) -> Token { + self.global + .or(self.long) + .or(self.outer) + .expect("prefix scan starts with a prefix") + } + + fn error_token(&self) -> Token { + self.long + .or(self.outer) + .or(self.global) + .unwrap_or_else(|| self.first_token()) + } + + fn flags(&self) -> PrefixFlags { + PrefixFlags { + global: self.global.is_some(), + long: self.long.is_some(), + outer: self.outer.is_some(), + } + } +} + +pub(crate) fn global_tag() -> Tag { + GLOBAL_TAG.get() +} + +pub(crate) fn long_tag() -> Tag { + LONG_TAG.get() +} + +pub(crate) fn outer_tag() -> Tag { + OUTER_TAG.get() +} + +pub(crate) fn relax_tag() -> Tag { + RELAX_TAG.get() +} + +pub(crate) fn global_assignment_tag() -> Tag { + GLOBAL_ASSIGNMENT_TAG.get() +} + +pub(crate) fn process_prefixes( + kind: PrefixKind, + token: Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result { + let mut prefixes = Prefixes::default(); + prefixes.add(kind, token); + + loop { + let Some(next) = input.next()? else { + return Err(input.fatal_error(error::SimpleTokenError::new( + prefixes.first_token(), + "prefix command must be followed by an assignable command", + ))); + }; + + if matches!(next.value(), token::Value::Space(_)) { + continue; + } + + if let token::Value::CommandRef(command_ref) = next.value() { + let tag = input.vm().commands_map.get_tag(&command_ref); + if tag == Some(relax_tag()) { + continue; + } + let prefix_kind = if tag == Some(global_tag()) { + Some(PrefixKind::Global) + } else if tag == Some(long_tag()) { + Some(PrefixKind::Long) + } else if tag == Some(outer_tag()) { + Some(PrefixKind::Outer) + } else { + None + }; + if let Some(prefix_kind) = prefix_kind { + prefixes.add(prefix_kind, next); + continue; + } + + let command = input.vm().commands_map.get_command(&command_ref); + let target_tag = input.vm().commands_map.get_tag(&command_ref); + let is_definition = target_tag == Some(texlang_stdlib::def::def_tag()); + let is_global_only = matches!(command, Some(Command::Variable(_) | Command::Font(_))) + || target_tag.is_some_and(super::arithmetic::is_arithmetic_tag) + || target_tag.is_some_and(|tag| { + [ + texlang_stdlib::alias::let_tag(), + texlang_stdlib::registers::countdef_tag(), + global_assignment_tag(), + ] + .contains(&tag) + }); + + if is_definition { + input.back(next); + return Ok(prefixes.flags()); + } + if is_global_only && prefixes.global.is_some() { + if prefixes.long.is_some() || prefixes.outer.is_some() { + input.back(next); + return Err(input.fatal_error(error::SimpleTokenError::new( + prefixes.error_token(), + "\\long and \\outer can only prefix macro definitions", + ))); + } + input.back(next); + return Ok(PrefixFlags { + global: true, + ..PrefixFlags::default() + }); + } + } else { + input.back(next); + } + + let message = if prefixes.long.is_some() || prefixes.outer.is_some() { + "\\long and \\outer can only prefix macro definitions" + } else if prefixes.global.is_some() { + "\\global must prefix an assignable command" + } else { + "prefix command must be followed by a valid command" + }; + return Err(input.fatal_error(error::SimpleTokenError::new( + prefixes.error_token(), + message, + ))); + } +} diff --git a/src/rust_typeset/engine/registers.rs b/src/rust_typeset/engine/registers.rs new file mode 100644 index 0000000..9bc127e --- /dev/null +++ b/src/rust_typeset/engine/registers.rs @@ -0,0 +1,63 @@ +use std::collections::HashMap; + +/// Sparse TeX register values with local/global group assignment semantics. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct RegisterTable { + values: HashMap, + zero: T, + groups: Vec>>, +} + +impl Default for RegisterTable { + fn default() -> Self { + Self { + values: HashMap::new(), + zero: T::default(), + groups: Vec::new(), + } + } +} + +impl RegisterTable { + pub(crate) fn get_index_ref(&self, index: usize) -> &T { + self.values.get(&index).unwrap_or(&self.zero) + } + + pub(crate) fn get_index_mut_ref(&mut self, index: usize) -> &mut T + where + T: Default, + { + self.values.entry(index).or_default() + } + + pub(crate) fn prepare_assignment(&mut self, index: usize, global: bool) { + if global { + for group in &mut self.groups { + group.remove(&index); + } + } else if let Some(group) = self.groups.last_mut() { + let previous = self.values.get(&index).cloned(); + group.entry(index).or_insert(previous); + } + } + + pub(crate) fn begin_group(&mut self) { + self.groups.push(HashMap::new()); + } + + pub(crate) fn end_group(&mut self) { + let Some(group) = self.groups.pop() else { + return; + }; + for (index, value) in group { + match value { + Some(value) => { + self.values.insert(index, value); + } + None => { + self.values.remove(&index); + } + } + } + } +} diff --git a/src/rust_typeset/engine/state.rs b/src/rust_typeset/engine/state.rs new file mode 100644 index 0000000..6cb26c7 --- /dev/null +++ b/src/rust_typeset/engine/state.rs @@ -0,0 +1,96 @@ +use std::ops::{Deref, DerefMut}; + +use super::{input::InputStack, registers::RegisterTable}; +use texrra_core::state::EngineSemanticState; + +/// TeX's `\\mag` parameter, stored as a ratio with 1000 meaning 1:1. +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +pub(crate) struct Magnification(i32); + +impl Magnification { + pub(crate) fn value(&self) -> i32 { + self.0 + } + + pub(crate) fn reference(&self) -> &i32 { + &self.0 + } + + pub(crate) fn reference_mut(&mut self) -> &mut i32 { + &mut self.0 + } +} + +impl Default for Magnification { + fn default() -> Self { + Self(1000) + } +} + +/// Runtime state for the current adapter around the Rust-owned TeX state. +/// +/// Registers that still use Texlang value types and source I/O remain in this +/// application layer. Field access to engine semantics forwards to the core. +#[derive(serde::Serialize, serde::Deserialize, Default)] +pub(crate) struct TeXEngineState { + #[serde(default, flatten)] + semantic: EngineSemanticState, + pub(crate) count_registers: RegisterTable, + pub(crate) dimen_registers: RegisterTable, + pub(crate) skip_registers: RegisterTable, + pub(crate) muskip_registers: RegisterTable, + pub(crate) token_registers: RegisterTable>, + #[serde(default)] + pub(crate) magnification: Magnification, + /// Next free index for registers allocated by `\newlength` and friends. + /// + /// The register tables are sparse, so allocation only needs to hand out + /// unused indices. Starting above the fixed compatibility registers keeps + /// style files and document-level allocations from colliding. + #[serde(default)] + pub(crate) next_skip_register: usize, + #[serde(skip)] + pub(crate) inputs: InputStack, +} + +impl Deref for TeXEngineState { + type Target = EngineSemanticState; + + fn deref(&self) -> &Self::Target { + &self.semantic + } +} + +impl DerefMut for TeXEngineState { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.semantic + } +} + +impl TeXEngineState { + pub(crate) fn begin_group(&mut self) { + self.semantic.begin_group(); + self.count_registers.begin_group(); + self.dimen_registers.begin_group(); + self.skip_registers.begin_group(); + self.muskip_registers.begin_group(); + self.token_registers.begin_group(); + } + + pub(crate) fn allocate_skip_register(&mut self) -> usize { + const FIRST_ALLOCATED_SKIP: usize = 1_000; + let index = self.next_skip_register.max(FIRST_ALLOCATED_SKIP); + self.next_skip_register = index + 1; + index + } + + pub(crate) fn end_group(&mut self) { + self.semantic.end_group(); + self.count_registers.end_group(); + self.dimen_registers.end_group(); + self.skip_registers.end_group(); + self.muskip_registers.end_group(); + self.token_registers.end_group(); + } +} diff --git a/src/rust_typeset/engine/texlang_dimension_adapter.rs b/src/rust_typeset/engine/texlang_dimension_adapter.rs new file mode 100644 index 0000000..2182ce0 --- /dev/null +++ b/src/rust_typeset/engine/texlang_dimension_adapter.rs @@ -0,0 +1,438 @@ +//! Temporary bridge from Texlang token streams to the Rust numeric scanners. + +use texlang::{ + token, + traits::TexlangState, + types::MuGlue, + variable::SupportedType, + vm::{self, TokenStream}, +}; +use texrra_core::{CatCode, MathCode, integer::IntegerTokenStream}; + +use super::{ + dimension::{ + self, DimensionScanError, DimensionTokenStream, InternalMathDimension, ScannedInteger, + }, + glue::TeXGlue, + token::EngineCatCode, +}; + +pub(crate) struct TexlangDimensionTokenStream<'a, S: TexlangState> { + input: &'a mut vm::ExpandedStream, + consumed: Vec, +} + +impl<'a, S: TexlangState> TexlangDimensionTokenStream<'a, S> { + pub(crate) fn new(input: &'a mut vm::ExpandedStream) -> Self { + Self { + input, + consumed: Vec::new(), + } + } + + pub(crate) fn rollback(&mut self) { + for token in self.consumed.drain(..).rev() { + self.input.back(token); + } + } + + fn variable_value(&mut self, token: token::Token) -> Result, vm::ShutdownSignal> + where + T: SupportedType + Copy, + { + let token::Value::CommandRef(command_ref) = token.value() else { + return Ok(None); + }; + let Some(texlang::command::Command::Variable(command)) = self + .input + .vm() + .commands_map + .get_command(&command_ref) + .cloned() + else { + return Ok(None); + }; + let Some(variable) = command.resolve_type::(token, self.input)? else { + return Ok(None); + }; + Ok(Some(*variable.get(self.input.state()))) + } +} + +impl IntegerTokenStream for TexlangDimensionTokenStream<'_, S> { + type Token = token::Token; + type Error = vm::ShutdownSignal; + + fn next_token(&mut self) -> Result, Self::Error> { + let token = self.input.next()?; + if let Some(token) = token { + self.consumed.push(token); + Ok(Some(token)) + } else { + Ok(None) + } + } + + fn back_token(&mut self, token: Self::Token) { + if self.consumed.last() == Some(&token) { + self.consumed.pop(); + } + self.input.back(token); + } + + fn character(&self, token: &Self::Token) -> Option<(char, EngineCatCode)> { + token.value().char_and_cat_code() + } + + fn is_space(&self, token: &Self::Token) -> bool { + matches!(token.value(), token::Value::Space(_)) + } + + fn is_command_reference(&self, token: &Self::Token) -> bool { + matches!(token.value(), token::Value::CommandRef(_)) + } + + fn control_sequence_name(&self, token: &Self::Token) -> Option { + let token::Value::CommandRef(token::CommandRef::ControlSequence(name)) = token.value() + else { + return None; + }; + self.input + .vm() + .cs_name_interner() + .resolve(name) + .map(str::to_owned) + } + + fn scan_internal_integer(&mut self, token: Self::Token) -> Result, Self::Error> { + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(value)); + } + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(i32::from(value))); + } + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(value as i32)); + } + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(value.0 as i32)); + } + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(value.0)); + } + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(value.width.0)); + } + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(value.0.width.0)); + } + Ok(None) + } +} + +impl DimensionTokenStream for TexlangDimensionTokenStream<'_, S> { + fn scan_internal_dimension( + &mut self, + token: Self::Token, + ) -> Result, Self::Error> { + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(value)); + } + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(value.width)); + } + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(common::Scaled(value))); + } + Ok(None) + } + + fn scan_internal_glue(&mut self, token: Self::Token) -> Result, Self::Error> { + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(TeXGlue::from(value))); + } + Ok(None) + } + + fn scan_internal_math_glue( + &mut self, + token: Self::Token, + ) -> Result, Self::Error> { + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(TeXGlue::from(value.0))); + } + Ok(None) + } + + fn scan_internal_math_dimension( + &mut self, + token: Self::Token, + ) -> Result, Self::Error> { + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(InternalMathDimension::GlueWidth(value.0.width))); + } + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(InternalMathDimension::Integer(value))); + } + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(InternalMathDimension::Integer(i32::from(value)))); + } + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(InternalMathDimension::Integer(value as i32))); + } + if let Some(value) = self.variable_value::(token.clone())? { + return Ok(Some(InternalMathDimension::Integer(value.0 as i32))); + } + Ok(None) + } + + fn em_width(&self) -> common::Scaled { + self.input.state().em_width() + } + + fn ex_height(&self) -> common::Scaled { + self.input.state().ex_height() + } + + fn magnification_ratio(&self) -> i32 { + self.input.state().magnification_ratio() + } +} + +pub(crate) fn scan_integer_with_token( + input: &mut vm::ExpandedStream, +) -> Result, DimensionScanError> { + let mut stream = TexlangDimensionTokenStream::new(input); + let result = dimension::scan_integer_with_token(&mut stream); + if matches!(result, Err(DimensionScanError::CompatibilityRequired)) { + stream.rollback(); + } + result +} + +pub(crate) fn try_scan_integer( + input: &mut vm::ExpandedStream, +) -> texlang::prelude::Result> { + let result = { + let mut stream = TexlangDimensionTokenStream::new(input); + let result = dimension::scan_integer(&mut stream); + if matches!(result, Err(DimensionScanError::CompatibilityRequired)) { + stream.rollback(); + } + result + }; + match result { + Ok(value) => Ok(Some(value)), + Err(DimensionScanError::Stream(signal)) => Err(signal), + Err(DimensionScanError::CompatibilityRequired) => Ok(None), + Err(error) => recover_integer_error(input, error).map(Some), + } +} + +pub(crate) fn try_scan_dimension( + input: &mut vm::ExpandedStream, +) -> texlang::prelude::Result> { + let result = { + let mut stream = TexlangDimensionTokenStream::new(input); + let result = dimension::scan_dimension(&mut stream, false); + if matches!( + result, + Err(DimensionScanError::CompatibilityRequired | DimensionScanError::IllegalUnit(_)) + ) { + stream.rollback(); + } + result + }; + match result { + Ok(dimension) => Ok(Some(dimension.value)), + Err(DimensionScanError::Stream(signal)) => Err(signal), + Err(DimensionScanError::CompatibilityRequired) => Ok(None), + Err(DimensionScanError::IllegalUnit(_)) => Ok(None), + Err(error) => recover_dimension_error(input, error).map(Some), + } +} + +pub(crate) fn try_scan_glue( + input: &mut vm::ExpandedStream, +) -> texlang::prelude::Result> { + let result = { + let mut stream = TexlangDimensionTokenStream::new(input); + let result = dimension::scan_glue(&mut stream); + if matches!( + result, + Err(DimensionScanError::CompatibilityRequired | DimensionScanError::IllegalUnit(_)) + ) { + stream.rollback(); + } + result + }; + match result { + Ok(glue) => Ok(Some(glue.into())), + Err(DimensionScanError::Stream(signal)) => Err(signal), + Err(DimensionScanError::CompatibilityRequired) => Ok(None), + Err(DimensionScanError::IllegalUnit(_)) => Ok(None), + Err(error) => recover_dimension_error(input, error).map(|width| { + Some(common::Glue { + width, + ..common::Glue::default() + }) + }), + } +} + +fn recover_integer_error( + input: &mut vm::ExpandedStream, + error: DimensionScanError, +) -> texlang::prelude::Result { + match error { + DimensionScanError::Stream(signal) => Err(signal), + DimensionScanError::CompatibilityRequired => unreachable!(), + DimensionScanError::MissingNumber(token) + | DimensionScanError::IllegalUnit(token) + | DimensionScanError::InvalidExpression(token) => { + input.error(texlang::parse::Error::new( + "an integer", + token, + "expected a TeX integer", + ))?; + Ok(0) + } + DimensionScanError::TooLarge { token, .. } => { + input.error( + texlang::parse::Error::new( + "an integer in range", + token, + "the integer is too large", + ) + .with_got_override("an integer that is too large"), + )?; + Ok(0) + } + } +} + +pub(crate) fn try_scan_math_glue( + input: &mut vm::ExpandedStream, +) -> texlang::prelude::Result> { + let result = { + let mut stream = TexlangDimensionTokenStream::new(input); + let result = dimension::scan_math_glue(&mut stream); + if matches!( + result, + Err(DimensionScanError::CompatibilityRequired | DimensionScanError::IllegalUnit(_)) + ) { + stream.rollback(); + } + result + }; + match result { + Ok(glue) => Ok(Some(MuGlue(glue.into()))), + Err(DimensionScanError::Stream(signal)) => Err(signal), + Err(DimensionScanError::CompatibilityRequired) => Ok(None), + Err(DimensionScanError::IllegalUnit(_)) => Ok(None), + Err(error) => recover_math_glue_error(input, error).map(|width| { + Some(MuGlue(common::Glue { + width, + ..common::Glue::default() + })) + }), + } +} + +fn recover_math_glue_error( + input: &mut vm::ExpandedStream, + error: DimensionScanError, +) -> texlang::prelude::Result { + match error { + DimensionScanError::Stream(signal) => Err(signal), + DimensionScanError::CompatibilityRequired => unreachable!(), + DimensionScanError::MissingNumber(token) => { + input.error(texlang::parse::Error::new( + "the beginning of a math glue value", + token, + "a math glue value starts with a number, a math glue variable, or \\\\muexpr", + ))?; + Ok(common::Scaled::ZERO) + } + DimensionScanError::IllegalUnit(token) => { + input.error(texlang::parse::Error::new( + "a math unit (mu)", + token, + "math glue values use mu units; stretch and shrink may also use fil, fill, or filll", + ))?; + Ok(common::Scaled::ZERO) + } + DimensionScanError::InvalidExpression(token) => { + input.error(texlang::parse::Error::new( + "a valid math glue expression", + token, + "check the operators, parentheses, units, and arithmetic range in \\\\muexpr", + ))?; + Ok(common::Scaled::ZERO) + } + DimensionScanError::TooLarge { token, negative } => { + input.error( + texlang::parse::Error::new( + "math glue in TeX's supported range", + token, + "the math glue value is too large", + ) + .with_got_override("math glue that's too large"), + )?; + Ok(if negative { + -common::Scaled::MAX_DIMEN + } else { + common::Scaled::MAX_DIMEN + }) + } + } +} + +fn recover_dimension_error( + input: &mut vm::ExpandedStream, + error: DimensionScanError, +) -> texlang::prelude::Result { + match error { + DimensionScanError::Stream(signal) => Err(signal), + DimensionScanError::CompatibilityRequired => unreachable!(), + DimensionScanError::MissingNumber(token) => { + input.error(texlang::parse::Error::new( + "the beginning of a dimension", + token, + "a dimension starts with a number or a dimension variable", + ))?; + Ok(common::Scaled::ZERO) + } + DimensionScanError::IllegalUnit(token) => { + input.error(texlang::parse::Error::new( + "a unit of measure", + token, + "dimensions can use pt, in, pc, cm, mm, bp, dd, cc, sp, em, or ex", + ))?; + Ok(common::Scaled::ZERO) + } + DimensionScanError::InvalidExpression(token) => { + input.error(texlang::parse::Error::new( + "a valid dimension expression", + token, + "check the operators, parentheses, and arithmetic range in the expression", + ))?; + Ok(common::Scaled::ZERO) + } + DimensionScanError::TooLarge { token, negative } => { + input.error( + texlang::parse::Error::new( + "a dimension in the range (-2^14pt, 2^14pt)", + token, + "the dimension is too large", + ) + .with_got_override("a dimension that's too large"), + )?; + Ok(if negative { + -common::Scaled::MAX_DIMEN + } else { + common::Scaled::MAX_DIMEN + }) + } + } +} diff --git a/src/rust_typeset/engine/token.rs b/src/rust_typeset/engine/token.rs new file mode 100644 index 0000000..71c6011 --- /dev/null +++ b/src/rust_typeset/engine/token.rs @@ -0,0 +1,2 @@ +pub(crate) use texrra_core::CatCode as EngineCatCode; +pub(crate) use texrra_core::{EngineCommandName, EngineToken, EngineTokenValue}; diff --git a/src/rust_typeset/engine/variable.rs b/src/rust_typeset/engine/variable.rs new file mode 100644 index 0000000..b22cd1f --- /dev/null +++ b/src/rust_typeset/engine/variable.rs @@ -0,0 +1,62 @@ +//! Arithmetic variable assignment semantics owned by the Rust engine. + +use texcraft_stdext::collections::groupingmap; +use texlang::{ + error, + parse::{OptionalEquals, Parsable}, + token, + traits::TexlangState, + variable::{self, SupportedType, TypedVariable}, + vm, +}; + +pub(crate) fn assign_arithmetic( + command: &variable::Command, + token: token::Token, + input: &mut vm::ExecutionInput, + scope: groupingmap::Scope, +) -> Option> { + if !command.is_arithmetic() { + return None; + } + + Some(assign(command, token, input, scope)) +} + +fn assign( + command: &variable::Command, + token: token::Token, + input: &mut vm::ExecutionInput, + scope: groupingmap::Scope, +) -> texlang::prelude::Result<()> { + let variable = command.resolve(token, input.as_mut())?; + input.with_operation( + token, + error::OperationKind::VariableAssignment, + |input| match variable { + variable::Variable::Int(variable) => assign_value(variable, input, scope), + variable::Variable::SmallInt(variable) => assign_value(variable, input, scope), + variable::Variable::Dimen(variable) => assign_value(variable, input, scope), + variable::Variable::Glue(variable) => assign_value(variable, input, scope), + variable::Variable::MuGlue(variable) => assign_value(variable, input, scope), + variable::Variable::CatCode(_) + | variable::Variable::MathCode(_) + | variable::Variable::TokenList(_) + | variable::Variable::Font(_) => unreachable!("non-arithmetic variable dispatched"), + }, + ) +} + +fn assign_value( + variable: TypedVariable, + input: &mut vm::ExecutionInput, + scope: groupingmap::Scope, +) -> texlang::prelude::Result<()> +where + S: TexlangState, + T: SupportedType, +{ + let (_, value) = <(OptionalEquals, T)>::parse(input)?; + variable.set(input, scope, value); + Ok(()) +} diff --git a/src/rust_typeset/frontend.rs b/src/rust_typeset/frontend.rs new file mode 100644 index 0000000..af35807 --- /dev/null +++ b/src/rust_typeset/frontend.rs @@ -0,0 +1,831 @@ +use std::{ + collections::hash_map::DefaultHasher, + env, + ffi::OsString, + fs, + hash::{Hash, Hasher}, + path::{Path, PathBuf}, + time::{SystemTime, UNIX_EPOCH}, +}; + +use super::{read_control_sequence, source_directory, tex_expansion}; +pub(super) use texrra_core::math_lowering::MathParseCache; + +const PRELUDE: &str = r#" +\def\makeatletter{\catcode64=11\relax} +\def\makeatother{\catcode64=12\relax} +\def\bgroup{\begingroup} +\def\egroup{\endgroup} +\def\geometry#1{\texrrageometry{#1}} +\def\begin#1{\texrrabegin{#1}} +\def\end#1{\texrraend{#1}} +\def\title#1{\texrrametadatastart{title}#1\texrrametadataend{title}} +\def\author#1{\texrrametadatastart{author}#1\texrrametadataend{author}} +\def\date#1{\texrrametadatastart{date}#1\texrrametadataend{date}} +\def\today{__TEXRRA_TODAY__} +\def\maketitle{\texrramaketitle} +\def\tableofcontents{} +\def\noindent{} +\def\allowbreak{\penalty0} +\def\nobreak{\penalty10000} +\def\centering{} +\def\raggedright{} +\def\raggedleft{} +\def\bibliographystyle#1{} +\def\textbf#1{\texrrastylestart{bold}#1\texrrastyleend{bold}} +\def\emph#1{\texrrastylestart{italic}#1\texrrastyleend{italic}} +\def\textit#1{\texrrastylestart{italic}#1\texrrastyleend{italic}} +\def\mathit#1{\texrramathfontstart{italic}#1\texrramathfontend} +\def\phantom#1{\texrramathphantomstart{both}#1\texrramathphantomend} +\def\hphantom#1{\texrramathphantomstart{horizontal}#1\texrramathphantomend} +\def\vphantom#1{\texrramathphantomstart{vertical}#1\texrramathphantomend} +\def\texttt#1{\texrrastylestart{monospace}#1\texrrastyleend{monospace}} +\def\underline#1{\texrramathaccentstart{underline}#1\texrramathaccentend} +\def\hat#1{\texrramathaccentstart{hat}#1\texrramathaccentend} +\def\widehat#1{\texrramathaccentstart{widehat}#1\texrramathaccentend} +\def\tilde#1{\texrramathaccentstart{tilde}#1\texrramathaccentend} +\def\widetilde#1{\texrramathaccentstart{widetilde}#1\texrramathaccentend} +\def\overbrace#1{\texrramathaccentstart{overbrace}#1\texrramathaccentend} +\def\underbrace#1{\texrramathaccentstart{underbrace}#1\texrramathaccentend} +\def\vec#1{\Umathaccent 0 2 "20D7 {#1}} +\def\overleftarrow#1{\Umathaccent 0 2 "20D6 {#1}} +\def\overrightarrow#1{\Umathaccent 0 2 "20D7 {#1}} +\def\overleftrightarrow#1{\Umathaccent 0 2 "20E1 {#1}} +\def\underleftarrow#1{\Umathaccent bottom 0 2 "20EE {#1}} +\def\underrightarrow#1{\Umathaccent bottom 0 2 "20EF {#1}} +\def\underleftrightarrow#1{\Umathaccent bottom 0 2 "034D {#1}} +\def\xleftarrow#1{\Umathaccent bottom 3 2 "20EE {#1}} +\def\xrightarrow#1{\Umathaccent bottom 3 2 "20EF {#1}} +\def\xleftrightarrow#1{\Umathaccent bottom 3 2 "034D {#1}} +\def\text#1{\texrramathfontstart{text}#1\texrramathfontend} +\def\item{\texrraitem} +\def\newpage{\texrrapagebreak} +\def\clearpage{\texrrapagebreak} +\def\pagebreak{\texrrapagebreak} +\def\label#1{\texrralabel{#1}} +\def\ref#1{\texrraref{#1}} +\def\nonumber{\texrranonumber} +\def\notag{\texrranonumber} +\def\tag{\texrratag} +\def\cite#1{\texrracite{#1}} +\def\citep#1{\texrracite{#1}} +\def\citet#1{\texrracite{#1}} +\def\nocite#1{} +\def\newblock{ } +\def\caption#1{\texrracaptionstart#1\texrracaptionend} +\def\href#1#2{#2} +\def\hline{\texrratablerule} +\def\toprule{\texrratablerule} +\def\midrule{\texrratablerule} +\def\bottomrule{\texrratablerule} +\def\cline#1{\texrratablerule} +\def\multicolumn#1#2#3{#3} +\def\&{\texrraampersand} +\def\LaTeX{LaTeX} +\def\TeX{TeX} +\def\\{\texrrarowbreak} +\def\[{\texrradisplaymathstart} +\def\]{\texrradisplaymathend} +\def\({\texrrainlinemathstart} +\def\){\texrrainlinemathend} +\def\frac#1#2{\texrramathfractionstart{automatic}{rule}{plain}#1\texrramathfractionsep#2\texrramathfractionend} +\def\dfrac#1#2{\texrramathfractionstart{display}{rule}{plain}#1\texrramathfractionsep#2\texrramathfractionend} +\def\tfrac#1#2{\texrramathfractionstart{text}{rule}{plain}#1\texrramathfractionsep#2\texrramathfractionend} +\def\binom#1#2{\texrramathfractionstart{automatic}{no-rule}{parens}#1\texrramathfractionsep#2\texrramathfractionend} +\def\dbinom#1#2{\texrramathfractionstart{display}{no-rule}{parens}#1\texrramathfractionsep#2\texrramathfractionend} +\def\tbinom#1#2{\texrramathfractionstart{text}{no-rule}{parens}#1\texrramathfractionsep#2\texrramathfractionend} +\def\mathrm#1{\texrramathfontstart{roman}#1\texrramathfontend} +\def\mathbf#1{\texrramathfontstart{bold-roman}#1\texrramathfontend} +\def\mathtt#1{\texrramathfontstart{monospace}#1\texrramathfontend} +\def\mathsf#1{\texrramathfontstart{sans-serif}#1\texrramathfontend} +\def\mathcal#1{\texrramathfontstart{calligraphic}#1\texrramathfontend} +\def\mathbb#1{\texrramathfontstart{blackboard}#1\texrramathfontend} +\def\mathfrak#1{\texrramathfontstart{fraktur}#1\texrramathfontend} +\def\boldsymbol#1{\texrramathfontstart{bold}#1\texrramathfontend} +\def\operatorname#1{\texrraoperatorstart#1\texrraoperatorend} +\def\stackrel#1#2{\mathrel{\mathop{#2}\limits^{#1}}} +\def\overset#1#2{\mathop{#2}\limits^{#1}} +\def\underset#1#2{\mathop{#2}\limits_{#1}} +\def\substack#1{\begin{smallmatrix}#1\end{smallmatrix}} +\def\mathord#1{\texrramathclassstart{ordinary}#1\texrramathclassend} +\def\mathop#1{\texrramathclassstart{operator}#1\texrramathclassend} +\def\mathbin#1{\texrramathclassstart{binary}#1\texrramathclassend} +\def\mathrel#1{\texrramathclassstart{relation}#1\texrramathclassend} +\def\mathopen#1{\texrramathclassstart{opening}#1\texrramathclassend} +\def\mathclose#1{\texrramathclassstart{closing}#1\texrramathclassend} +\def\mathpunct#1{\texrramathclassstart{punctuation}#1\texrramathclassend} +\def\mathinner#1{\texrramathclassstart{inner}#1\texrramathclassend} +\def\overline#1{\texrramathaccentstart{overline}#1\texrramathaccentend} +\def\langle{⟨} +\def\rangle{⟩} +\def\{{\texrraopenbrace} +\def\}{\texrraclosebrace} +\def\lbrace{\texrraopenbrace} +\def\rbrace{\texrraclosebrace} +\def\lfloor{⌊} +\def\rfloor{⌋} +\def\lceil{⌈} +\def\rceil{⌉} +\def\vert{|} +\def\Vert{‖} +\def\|{‖} +\def\alpha{α} +\def\beta{β} +\def\gamma{γ} +\def\delta{δ} +\def\epsilon{ε} +\def\zeta{ζ} +\def\eta{η} +\def\theta{θ} +\def\vartheta{ϑ} +\def\iota{ι} +\def\kappa{κ} +\def\lambda{λ} +\def\mu{μ} +\def\nu{ν} +\def\xi{ξ} +\def\pi{π} +\def\varpi{ϖ} +\def\rho{ρ} +\def\varrho{ϱ} +\def\sigma{σ} +\def\varsigma{ς} +\def\tau{τ} +\def\upsilon{υ} +\def\phi{φ} +\def\varphi{ϕ} +\def\chi{χ} +\def\psi{ψ} +\def\omega{ω} +\def\Gamma{Γ} +\def\Delta{Δ} +\def\Theta{Θ} +\def\Xi{Ξ} +\def\Lambda{Λ} +\def\Pi{Π} +\def\Upsilon{Υ} +\def\Sigma{Σ} +\def\Phi{Φ} +\def\Psi{Ψ} +\def\Omega{Ω} +\def\times{×} +\def\cdot{·} +\def\pm{±} +\def\leq{≤} +\def\le{≤} +\def\geq{≥} +\def\ge{≥} +\def\neq{≠} +\def\approx{≈} +\def\equiv{≡} +\def\in{∈} +\def\notin{∉} +\def\partial{∂} +\def\nabla{∇} +\def\forall{∀} +\def\exists{∃} +\def\to{→} +\def\rightarrow{→} +\def\leftarrow{←} +\def\Rightarrow{⇒} +\def\Leftrightarrow{⇔} +\def\ldots{…} +\def\cdots{⋯} +\def\varepsilon{ϵ} +\def\infty{∞} +\def\sim{∼} +\def\simeq{≃} +\def\cong{≅} +\def\propto{∝} +\def\ll{≪} +\def\gg{≫} +\def\subset{⊂} +\def\subseteq{⊆} +\def\supset{⊃} +\def\supseteq{⊇} +\def\cup{∪} +\def\cap{∩} +\def\setminus{∖} +\def\emptyset{∅} +\def\varnothing{∅} +\def\wedge{∧} +\def\vee{∨} +\def\neg{¬} +\def\lnot{¬} +\def\oplus{⊕} +\def\otimes{⊗} +\def\perp{⊥} +\def\parallel{∥} +\def\angle{∠} +\def\triangle{△} +\def\ddots{⋱} +\def\vdots{⋮} +\def\hbar{ℏ} +\def\ell{ℓ} +\def\aleph{ℵ} +\def\imath{ı} +\def\jmath{ȷ} +\def\dagger{†} +\def\ddagger{‡} +\def\star{⋆} +\def\ast{∗} +\def\circ{∘} +\def\bullet{•} +\def\ldots{…} +\def\textdegree{°} +\def\degree{°} +\def\S{§} +\def\P{¶} +\def\copyright{©} +\def\pounds{£} +\def\sum{∑} +\def\prod{∏} +\def\int{∫} +\def\oint{∮} +\def\sin{\texrraoperatorstart sin\texrraoperatorend} +\def\cos{\texrraoperatorstart cos\texrraoperatorend} +\def\tan{\texrraoperatorstart tan\texrraoperatorend} +\def\log{\texrraoperatorstart log\texrraoperatorend} +\def\ln{\texrraoperatorstart ln\texrraoperatorend} +\def\exp{\texrraoperatorstart exp\texrraoperatorend} +\def\lim{\texrraoperatorstart lim\texrraoperatorend} +\def\max{\texrraoperatorstart max\texrraoperatorend} +\def\min{\texrraoperatorstart min\texrraoperatorend} +\def\quad{\hskip1em\relax} +\def\qquad{\hskip2em\relax} +\def\,{\texrramathspace{3}} +\def\:{\texrramathspace{4}} +\def\;{\texrramathspace{5}} +\def\!{\texrramathspace{-3}} +\def\big#1{\texrramathmanualdelimiter{17}{ordinary}#1} +\def\Big#1{\texrramathmanualdelimiter{23}{ordinary}#1} +\def\bigg#1{\texrramathmanualdelimiter{29}{ordinary}#1} +\def\Bigg#1{\texrramathmanualdelimiter{35}{ordinary}#1} +\def\bigl#1{\texrramathmanualdelimiter{17}{opening}#1} +\def\Bigl#1{\texrramathmanualdelimiter{23}{opening}#1} +\def\biggl#1{\texrramathmanualdelimiter{29}{opening}#1} +\def\Biggl#1{\texrramathmanualdelimiter{35}{opening}#1} +\def\bigm#1{\texrramathmanualdelimiter{17}{relation}#1} +\def\Bigm#1{\texrramathmanualdelimiter{23}{relation}#1} +\def\biggm#1{\texrramathmanualdelimiter{29}{relation}#1} +\def\Biggm#1{\texrramathmanualdelimiter{35}{relation}#1} +\def\bigr#1{\texrramathmanualdelimiter{17}{closing}#1} +\def\Bigr#1{\texrramathmanualdelimiter{23}{closing}#1} +\def\biggr#1{\texrramathmanualdelimiter{29}{closing}#1} +\def\Biggr#1{\texrramathmanualdelimiter{35}{closing}#1} + +% ---- LaTeX compatibility layer ------------------------------------------- +\def\ProvidesClass#1{} +\def\ProvidesPackage#1{} +\def\ProvidesFile#1{} +\def\rmdefault{cmr} +\def\sfdefault{cmss} +\def\ttdefault{cmtt} +\def\z@{0pt} +\def\p@{1pt} +\def\@plus{plus} +\def\@minus{minus} +\def\@xpt{10pt} +\def\@ixpt{9pt} +\def\@xipt{11pt} +\def\@xiipt{12pt} +\def\@xivpt{14pt} +\def\@xviipt{17pt} +\def\@xxpt{20pt} +\def\@xxvpt{25pt} +\def\@viipt{7pt} +\def\@viiipt{8pt} +\def\@vipt{6pt} +\def\@setfontsize#1#2#3{} +\def\normalsize{} +\def\small{} +\def\footnotesize{} +\def\scriptsize{} +\def\tiny{} +\def\large{} +\def\Large{} +\def\LARGE{} +\def\huge{} +\def\Huge{} +\def\flushbottom{} +\def\raggedbottom{} +\def\sloppy{} +\def\fussy{} +\def\protect{} +\def\leavevmode{} +\def\ignorespaces{} +\def\unskip{} +\def\addvspace#1{\vskip#1\relax} +\def\addpenalty#1{} +\def\medskipamount{6pt plus 2pt minus 2pt} +\def\smallskipamount{3pt plus 1pt minus 1pt} +\def\bigskipamount{12pt plus 4pt minus 4pt} +\def\medskip{\vskip6pt} +\def\smallskip{\vskip3pt} +\def\bigskip{\vskip12pt} +\def\textwidth{160mm} +\def\textheight{247mm} +\def\linewidth{\textwidth} +\def\columnwidth{\textwidth} +\def\smallbreak{\smallskip} +\def\medbreak{\medskip} +\def\bigbreak{\bigskip} +\def\tableofcontents{} +\def\listoffigures{} +\def\listoftables{} +\def\enspace{\hskip0.5em\relax} +\def\thinspace{\hskip0.16667em\relax} +\def\negthinspace{\hskip-0.16667em\relax} +\def\medspace{\hskip0.22222em\relax} +\def\negmedspace{\hskip-0.22222em\relax} +\def\thickspace{\hskip0.27778em\relax} +\def\negthickspace{\hskip-0.27778em\relax} +\def\space{ } +\def\nobreakspace{ } +\def\ { } +\def~{ } +\def\AtBeginDocument#1{#1} +\def\newgeometry#1{\texrrageometry{#1}} +\def\fancyhf{} +\def\fancyheadoffset#1{} +\def\fancyhead#1{} +\def\fancyfoot#1{} +\def\lhead#1{} +\def\chead#1{} +\def\rhead#1{} +\def\lfoot#1{} +\def\cfoot#1{} +\def\rfoot#1{} +\def\headrulewidth{0.4pt} +\def\footrulewidth{0pt} +\def\pagestyle#1{} +\def\thispagestyle#1{} +\def\thepage{1} +\def\hypersetup#1{} +\def\microtypesetup#1{} +\def\urlstyle#1{} +\def\fnsymbol#1{*} +\def\thefootnote{*} +\def\footnoterule{} +\def\footnote#1{} +\def\thanks#1{} +\def\@title{} +\def\@author{} +\def\@date{} +\def\@thanks{} +\def\@makefntext#1{} +\def\@makefnmark{} +\def\@thefnmark{} +\def\sc{} +\def\sf{} +\def\sl{} +\def\em{} +\def\scshape{\texrrascshape} +\def\S{§} +\def\P{¶} +\def\dag{†} +\def\ddag{‡} +\def\copyright{©} +\def\textbullet{•} +\def\textregistered{®} +\def\texttrademark{™} +\def\ldots{…} +\def\dots{…} +\def\textendash{–} +\def\textemdash{—} +\def\textquoteleft{‘} +\def\textquoteright{’} +\def\textquotedblleft{“} +\def\textquotedblright{”} +\def\textrm#1{{\rmfamily #1}} +\def\textup#1{{\upshape #1}} +\def\textmd#1{{\mdseries #1}} +\def\textsl#1{{\slshape #1}} +\def\textnormal#1{{\normalfont #1}} +\def\em{\itshape} +\def\ss{ß} +\def\ae{æ} +\def\AE{Æ} +\def\oe{œ} +\def\OE{Œ} +\def\aa{å} +\def\AA{Å} +\def\o{ø} +\def\O{Ø} +\def\l{ł} +\def\L{Ł} +\def\i{ı} +\def\textasciitilde{~} +\def\textasciicircum{^} +\def\textless{<} +\def\textgreater{>} +\def\textbar{|} +\def\textunderscore{_} +\def\guillemotleft{«} +\def\guillemotright{»} +\def\textquotesingle{'} +\def\texteuro{€} +\def\textsterling{£} +\def\textyen{¥} +\def\textcent{¢} +\def\textdegree{°} +\def\textpm{±} +\def\textmu{µ} +\def\textperthousand{‰} +\def\textonesuperior{¹} +\def\texttwosuperior{²} +\def\textthreesuperior{³} +\def\textonehalf{½} +\def\textonequarter{¼} +\def\textthreequarters{¾} +\def\textordfeminine{ª} +\def\textordmasculine{º} +\def\textohm{Ω} +\def\textcelsius{°C} +\def\checkmark{✓} +\def\textvisiblespace{␣} +\def\textbrokenbar{¦} +\def\textdagger{†} +\def\textdaggerdbl{‡} +\def\textperiodcentered{·} +\def\textsection{§} +\def\textparagraph{¶} +\def\sffamily{} +\def\textsc#1{{\texrrascshape #1}} +\def\nicefrac#1#2{#1/#2} +\def\cref#1{\texrraref{#1}} +\def\Cref#1{\texrraref{#1}} +\def\doi#1{#1} +\def\dots{...} +\def\textellipsis{...} +\def\and{ } +\def\And{ } +\def\AND{ } +\def\ifhmode{\iftrue} +\def\paragraph#1{\par\texrraheadingstart{3}#1\texrraheadingend\par} +\def\subparagraph#1{\par\texrraheadingstart{3}#1\texrraheadingend\par} +\def\@startsection#1#2#3#4#5#6#7{\par\texrraheadingstart{#2}#7\texrraheadingend\par} +\def\setlength#1#2{#1=#2\relax} +\def\addtolength#1#2{\advance#1#2\relax} +\def\stepcounter#1{} +\def\refstepcounter#1{} +\def\value#1{0} +\def\enlargethispage#1{} +\def\appendix{} +\def\listoffigures{} +\def\listoftables{} +\def\abstractname{Abstract} +\def\refname{References} +\def\bibname{References} +\def\figurename{Figure} +\def\tablename{Table} +\def\contentsname{Contents} +\def\keywords#1{\par\noindent\textbf{Keywords: }#1\par} +\def\hbox#1{#1} +\def\rule{\texrrarule} +\skipdef\parindent=100 +\skipdef\parskip=101 +\skipdef\baselineskip=102 +\skipdef\lineskip=103 +\skipdef\rightskip=104 +\skipdef\leftskip=105 +\skipdef\parfillskip=106 +\skipdef\topskip=107 +\skipdef\topsep=108 +\skipdef\partopsep=109 +\skipdef\itemsep=110 +\skipdef\parsep=111 +\skipdef\abovecaptionskip=112 +\skipdef\belowcaptionskip=113 +\skipdef\footnotesep=114 +\skipdef\leftmargin=115 +\skipdef\leftmarginii=116 +\skipdef\leftmarginiii=117 +\skipdef\leftmargini=122 +\skipdef\leftmarginiv=123 +\skipdef\leftmarginv=124 +\skipdef\leftmarginvi=125 +\skipdef\labelsep=118 +\skipdef\labelwidth=119 +\skipdef\itemindent=120 +\skipdef\listparindent=121 +\countdef\widowpenalty=200 +\countdef\clubpenalty=201 +\countdef\displaywidowpenalty=202 +\countdef\brokenpenalty=203 +\countdef\footins=204 +\countdef\pretolerance=205 +\countdef\tolerance=206 +\countdef\hbadness=207 +\countdef\vbadness=208 +\countdef\looseness=209 +\def\topfraction{0.7} +\def\bottomfraction{0.3} +\def\textfraction{0.2} +\def\floatpagefraction{0.5} +\def\dbltopfraction{0.7} +\def\arraystretch{1} +\def\tabcolsep{6pt} +\def\arrayrulewidth{0.4pt} +\def\doublerulesep{2pt} +\def\extrarowheight{0pt} +"#; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct PreprocessedSource { + source: tex_expansion::ExpandedSource, + file_name: String, + prelude: String, + style_search_path: Option, + cacheable: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct ExpandedTexSource { + source: tex_expansion::ExpandedSource, + dependencies: Vec, + cacheable: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct LoweredDocumentSource { + pub(super) source: tex_expansion::ExpandedTokenStream, + pub(super) dependencies: Vec, + pub(super) cacheable: bool, +} + +struct SourceLines { + origin: PathBuf, + line_starts: Vec, + base_line: usize, + base_column: usize, +} + +struct PreprocessOutput { + source: tex_expansion::ExpandedSource, + cacheable: bool, +} + +impl SourceLines { + fn new(source: &str, origin: &Path, base: tex_expansion::SourceLocation) -> Self { + let mut line_starts = vec![0]; + line_starts.extend( + source + .match_indices('\n') + .map(|(index, _)| index.saturating_add(1)), + ); + Self { + origin: origin.to_path_buf(), + line_starts, + base_line: base.line, + base_column: base.column, + } + } + + fn line_index_at(&self, offset: usize) -> usize { + self.line_starts + .partition_point(|line_start| *line_start <= offset) + .saturating_sub(1) + } + + fn location_at(&self, source: &str, offset: usize) -> tex_expansion::SourceLocation { + let line_index = self.line_index_at(offset); + let line_start = self.line_starts[line_index]; + let column = source[line_start..offset].chars().count() + + if line_index == 0 { self.base_column } else { 0 }; + tex_expansion::SourceLocation { + origin: tex_expansion::SourceOrigin::File(self.origin.clone()), + line: self.base_line + line_index, + column, + } + } +} + +fn append_source_range( + output: &mut tex_expansion::ExpandedSource, + source: &str, + lines: &SourceLines, + range: std::ops::Range, +) { + let mut cursor = range.start; + while cursor < range.end { + let line_index = lines.line_index_at(cursor); + let line_end = lines + .line_starts + .get(line_index + 1) + .copied() + .unwrap_or(range.end) + .min(range.end); + let end = line_end.max(cursor + 1).min(range.end); + let output_start = output.text.len(); + output.text.push_str(&source[cursor..end]); + output.segments.push(tex_expansion::SourceSegment { + output: output_start..output.text.len(), + location: lines.location_at(source, cursor), + column_advances: true, + column_character_starts: source[cursor..end] + .char_indices() + .map(|(offset, _)| offset) + .collect(), + }); + cursor = end; + } +} + +fn preprocess_latex(source: &str, source_path: &Path) -> Result { + let lines = SourceLines::new( + source, + source_path, + tex_expansion::SourceLocation { + origin: tex_expansion::SourceOrigin::File(source_path.to_path_buf()), + line: 1, + column: 0, + }, + ); + let mut expanded = tex_expansion::ExpandedSource { + text: String::with_capacity(source.len()), + segments: Vec::new(), + events: Vec::new(), + items: Vec::new(), + }; + append_source_range(&mut expanded, source, &lines, 0..source.len()); + Ok(PreprocessOutput { + source: expanded, + cacheable: can_cache_frontend_snapshot(source), + }) +} + +fn current_date_utc() -> String { + let days = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() as i64 + / 86_400; + let shifted_days = days + 719_468; + let era = if shifted_days >= 0 { + shifted_days + } else { + shifted_days - 146_096 + } / 146_097; + let day_of_era = shifted_days - era * 146_097; + let year_of_era = + (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let mut year = year_of_era + era * 400; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let month_part = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * month_part + 2) / 5 + 1; + let month = month_part + if month_part < 10 { 3 } else { -9 }; + year += i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02}") +} + +pub(super) fn can_cache_frontend_snapshot(source: &str) -> bool { + let dependency_commands = [ + "\\include", + "\\endinput", + "\\@input", + "\\@@input", + "\\InputIfFileExists", + "\\IfFileExists", + "\\openin", + "\\read", + "\\openout", + "\\closeout", + "\\write", + "\\immediate", + "\\message", + "\\typeout", + "\\errmessage", + "\\special", + "\\time", + "\\day", + "\\month", + "\\year", + "\\csname", + "\\scantokens", + "\\uppercase", + "\\lowercase", + "\\lccode", + "\\uccode", + "\\endlinechar", + "\\catcode", + "\\makeatletter", + ]; + let mut cursor = 0usize; + while cursor < source.len() { + if source[cursor..].starts_with('%') { + cursor = source[cursor..] + .find('\n') + .map_or(source.len(), |offset| cursor + offset + 1); + continue; + } + if source[cursor..].starts_with('\\') { + let (command, after) = read_control_sequence(source, cursor); + if dependency_commands.contains(&command.as_str()) { + return false; + } + cursor = after; + continue; + } + let character = source[cursor..] + .chars() + .next() + .expect("valid UTF-8 boundary"); + cursor += character.len_utf8(); + } + true +} + +pub(super) fn dependencies_unchanged(dependencies: &[tex_expansion::SourceDependency]) -> bool { + dependencies.iter().all(|dependency| { + fs::read_to_string(&dependency.path).is_ok_and(|contents| contents == dependency.contents) + }) +} + +pub(super) fn style_lookup_fingerprint(file_name: &str) -> u64 { + let mut hasher = DefaultHasher::new(); + let directories = std::iter::once(source_directory(file_name).to_path_buf()).chain( + env::var_os("TEXRRA_STY_DIR") + .into_iter() + .flat_map(|paths| env::split_paths(&paths).collect::>()), + ); + for directory in directories { + directory.hash(&mut hasher); + match fs::read_dir(&directory) { + Ok(entries) => { + true.hash(&mut hasher); + let mut style_names = entries + .filter_map(Result::ok) + .map(|entry| entry.file_name()) + .filter(|name| Path::new(name).extension().is_some_and(|ext| ext == "sty")) + .collect::>(); + style_names.sort(); + style_names.hash(&mut hasher); + } + Err(_) => false.hash(&mut hasher), + } + } + hasher.finish() +} + +pub(super) fn date_stamp() -> String { + current_date_utc() +} + +pub(super) fn preprocess(source: &str, file_name: &str) -> Result { + let prelude = PRELUDE.replace("__TEXRRA_TODAY__", ¤t_date_utc()); + let output = preprocess_latex(source, Path::new(file_name))?; + Ok(PreprocessedSource { + source: output.source, + file_name: file_name.to_string(), + prelude, + style_search_path: env::var_os("TEXRRA_STY_DIR"), + cacheable: output.cacheable, + }) +} + +pub(super) fn expand_tex( + source: PreprocessedSource, + cache: &mut tex_expansion::ExpansionCache, +) -> Result { + let PreprocessedSource { + source, + file_name, + prelude, + cacheable: preprocess_cacheable, + style_search_path, + } = source; + let output = tex_expansion::expand( + source, + &file_name, + &prelude, + cache, + preprocess_cacheable, + style_search_path, + style_lookup_fingerprint(&file_name), + Vec::new(), + )?; + let cacheable = preprocess_cacheable + && output + .dependencies + .iter() + .all(|dependency| can_cache_frontend_snapshot(&dependency.contents)); + Ok(ExpandedTexSource { + source: output.source, + dependencies: output.dependencies, + cacheable, + }) +} + +pub(super) fn lower_math( + source: ExpandedTexSource, + math_parse_cache: &mut MathParseCache, +) -> Result { + let expanded = source.source.into_token_stream(); + let collected = texrra_core::math_lowering::lower_math(expanded, math_parse_cache)?; + Ok(LoweredDocumentSource { + source: collected, + dependencies: source.dependencies, + cacheable: source.cacheable, + }) +} diff --git a/src/rust_typeset/math_font.rs b/src/rust_typeset/math_font.rs new file mode 100644 index 0000000..9d9486b --- /dev/null +++ b/src/rust_typeset/math_font.rs @@ -0,0 +1,1689 @@ +use std::{ + collections::{HashMap, HashSet}, + fs, + hash::{Hash, Hasher}, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; + +use genpdf::{Mm, style::Style}; +use image::{DynamicImage, Rgba, RgbaImage}; +use texrra_core::math_constants::{ + MathConstants, MathFractionParameters, MathLimitParameters, MathScriptParameters, + fraction_parameters, limit_parameters, overbar_parameters, radical_degree_parameters, + radical_parameters, script_parameters, underbar_parameters, +}; +use texrra_core::math_glyph::{self, MathGlyphMetrics, MathKernCorner, MathKernTable}; +use ttf_parser::{GlyphId, OutlineBuilder}; + +use super::{MathStyle, PDF_POINTS_PER_INCH}; + +#[derive(Clone)] +pub(super) struct MathFontMetrics { + units_per_em: f64, + x_height: Option, + constants: Option, + font_bytes: Option>, + math_alphanumeric_glyphs: HashSet, + glyph_fonts: [GlyphFont; 4], + custom_glyph_fonts: HashMap, + math_glyph_cache: Arc>>>, + pub(super) fingerprint: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct MathGlyphCacheKey { + font_bytes: usize, + character: char, +} + +#[derive(Clone, Debug)] +struct GlyphFont { + bytes: Arc<[u8]>, + units_per_em: f64, + x_height: Option, + has_italic_corrections: bool, + math_alphanumeric_glyphs: HashSet, + constants: Option, +} + +pub(super) struct RasterizedMathGlyph { + pub(super) image: DynamicImage, + pub(super) width: Mm, + pub(super) height: Mm, + pub(super) offset_x: Mm, + pub(super) offset_y: Mm, + pub(super) advance: Mm, +} + +fn core_math_kern(kern: Option>) -> Option { + let kern = kern?; + Some(MathKernTable { + correction_heights: (0..kern.count()) + .map(|index| kern.height(index).map(|height| height.value)) + .collect(), + values: (0..=kern.count()) + .map(|index| kern.kern(index).map(|value| value.value)) + .collect(), + }) +} + +fn read_math_glyph_metrics( + glyph_info: ttf_parser::math::GlyphInfo<'_>, + glyph: GlyphId, +) -> MathGlyphMetrics { + let kern_info = glyph_info + .kern_infos + .and_then(|kern_infos| kern_infos.get(glyph)); + let (top_right_kern, top_left_kern, bottom_right_kern, bottom_left_kern) = + kern_info.map_or((None, None, None, None), |kern_info| { + ( + kern_info.top_right, + kern_info.top_left, + kern_info.bottom_right, + kern_info.bottom_left, + ) + }); + + MathGlyphMetrics { + italic_correction: glyph_info.italic_corrections.map(|corrections| { + corrections + .get(glyph) + .map_or(0, |correction| correction.value) + }), + top_accent_attachment: glyph_info + .top_accent_attachments + .and_then(|attachments| attachments.get(glyph)) + .map(|attachment| attachment.value), + top_right_kern: core_math_kern(top_right_kern), + top_left_kern: core_math_kern(top_left_kern), + bottom_right_kern: core_math_kern(bottom_right_kern), + bottom_left_kern: core_math_kern(bottom_left_kern), + } +} + +fn load_glyph_font(path: &Path) -> Result { + let bytes = fs::read(path) + .map_err(|error| format!("could not read math glyph font {}: {error}", path.display()))?; + let face = ttf_parser::Face::parse(&bytes, 0).map_err(|error| { + format!( + "could not parse math glyph font {}: {error}", + path.display() + ) + })?; + let has_italic_corrections = face + .tables() + .math + .and_then(|math| math.glyph_info) + .and_then(|glyph_info| glyph_info.italic_corrections) + .is_some(); + let units_per_em = f64::from(face.units_per_em()); + let x_height = face.x_height().filter(|value| *value > 0).or_else(|| { + face.glyph_index('x') + .and_then(|glyph| face.glyph_bounding_box(glyph)) + .map(|bounds| bounds.y_max) + .filter(|value| *value > 0) + }); + let math_alphanumeric_glyphs = math_alphanumeric_characters() + .filter(|character| face.glyph_index(*character).is_some()) + .collect(); + let constants = face + .tables() + .math + .and_then(|math| math.constants) + .map(MathConstants::from_ttf); + drop(face); + Ok(GlyphFont { + bytes: Arc::<[u8]>::from(bytes), + units_per_em, + x_height, + has_italic_corrections, + math_alphanumeric_glyphs, + constants, + }) +} + +fn math_alphanumeric_characters() -> impl Iterator { + (0x1D400..=0x1D7FF) + .chain([ + 0x2102, 0x210A, 0x210B, 0x210C, 0x210D, 0x210E, 0x2110, 0x2111, 0x2112, 0x2113, 0x2115, + 0x2119, 0x211A, 0x211B, 0x211C, 0x211D, 0x2124, 0x212C, 0x212D, 0x212F, 0x2130, 0x2131, + 0x2133, 0x2134, + ]) + .filter_map(char::from_u32) +} + +fn rasterize_math_glyph( + bytes: &[u8], + units_per_em: f64, + character: char, + font_size: u8, +) -> Option { + const RASTER_DPI: f64 = 600.0; + const MAX_BITMAP_PIXELS: u64 = 4_000_000; + const SAMPLE_POINTS: [(f32, f32); 4] = [(0.25, 0.25), (0.75, 0.25), (0.25, 0.75), (0.75, 0.75)]; + + if units_per_em <= 0.0 { + return None; + } + let face = ttf_parser::Face::parse(bytes, 0).ok()?; + let glyph_id = face.glyph_index(character)?; + let bounds = face.glyph_bounding_box(glyph_id)?; + let advance = f64::from(face.glyph_hor_advance(glyph_id)?); + let millimeters_per_unit = + f64::from(font_size) * 25.4 / (f64::from(super::PDF_POINTS_PER_INCH) * units_per_em); + let pixels_per_unit = RASTER_DPI * millimeters_per_unit / 25.4; + if !pixels_per_unit.is_finite() || pixels_per_unit <= 0.0 { + return None; + } + + let ink_width = f64::from(bounds.x_max - bounds.x_min); + let ink_height = f64::from(bounds.y_max - bounds.y_min); + if ink_width <= 0.0 || ink_height <= 0.0 { + return None; + } + let width = (ink_width * pixels_per_unit).ceil() as u32 + 2; + let height = (ink_height * pixels_per_unit).ceil() as u32 + 2; + if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_BITMAP_PIXELS { + return None; + } + + let mut outline = RasterOutline::new( + pixels_per_unit, + 1.0 - f64::from(bounds.x_min) * pixels_per_unit, + 1.0 + f64::from(bounds.y_max) * pixels_per_unit, + ); + face.outline_glyph(glyph_id, &mut outline)?; + outline.finish_contour(); + if outline.contours.is_empty() { + return None; + } + + let mut bitmap = RgbaImage::from_pixel(width, height, Rgba([0, 0, 0, 0])); + for y in 0..height { + for x in 0..width { + let covered = SAMPLE_POINTS + .iter() + .filter(|(sample_x, sample_y)| { + inside_nonzero_winding( + &outline.contours, + x as f32 + sample_x, + y as f32 + sample_y, + ) + }) + .count(); + if covered > 0 { + bitmap.put_pixel( + x, + y, + Rgba([0, 0, 0, (covered * 255 / SAMPLE_POINTS.len()) as u8]), + ); + } + } + } + + let millimeters_per_pixel = 25.4 / RASTER_DPI; + Some(RasterizedMathGlyph { + image: DynamicImage::ImageRgba8(bitmap), + width: Mm::from(f64::from(width) * millimeters_per_pixel), + height: Mm::from(f64::from(height) * millimeters_per_pixel), + offset_x: Mm::from(f64::from(bounds.x_min) * millimeters_per_unit - millimeters_per_pixel), + offset_y: Mm::from(-f64::from(bounds.y_max) * millimeters_per_unit - millimeters_per_pixel), + advance: Mm::from(advance * millimeters_per_unit), + }) +} + +pub(super) struct StretchedDelimiter { + pub(super) image: DynamicImage, + pub(super) width: Mm, + pub(super) height: Mm, + pub(super) advance_extent: Mm, + pub(super) layout_width: Mm, + pub(super) layout_height: Mm, + pub(super) image_offset_x: Mm, + pub(super) image_offset_y: Mm, + pub(super) is_assembly: bool, + pub(super) baseline_from_top: Option, +} + +pub(super) struct MathScriptMetrics { + pub(super) subscript_top_max: Mm, + pub(super) subscript_baseline_drop_min: Mm, + pub(super) subscript_shift_down: Mm, + pub(super) superscript_bottom_min: Mm, + pub(super) superscript_baseline_drop_max: Mm, + pub(super) superscript_bottom_max_with_subscript: Mm, + pub(super) superscript_shift_up: Mm, + pub(super) superscript_shift_up_cramped: Mm, + pub(super) sub_superscript_gap_min: Mm, + pub(super) space_after_script: Mm, +} + +pub(super) struct MathFractionMetrics { + pub(super) numerator_shift_up: Mm, + pub(super) denominator_shift_down: Mm, + pub(super) numerator_gap_min: Mm, + pub(super) denominator_gap_min: Mm, + pub(super) rule_thickness: Mm, + pub(super) stack_gap_min: Mm, + pub(super) axis_height: Mm, +} + +pub(super) struct MathLimitMetrics { + pub(super) upper_gap_min: Mm, + pub(super) upper_baseline_rise_min: Mm, + pub(super) lower_gap_min: Mm, + pub(super) lower_baseline_drop_min: Mm, + pub(super) outer_padding: Mm, +} + +impl MathFontMetrics { + pub(super) fn load( + path: &Path, + require_math_constants: bool, + glyph_font_paths: &[std::path::PathBuf; 4], + ) -> Result { + let bytes = fs::read(path).map_err(|error| { + format!( + "could not read math metrics font {}: {error}", + path.display() + ) + })?; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + bytes.hash(&mut hasher); + let fingerprint = hasher.finish(); + let face = ttf_parser::Face::parse(&bytes, 0).map_err(|error| { + format!( + "could not parse math metrics font {}: {error}", + path.display() + ) + })?; + let math_table = face.tables().math; + let constants = math_table + .and_then(|table| table.constants) + .map(MathConstants::from_ttf); + let has_math_table = math_table.is_some(); + if require_math_constants && constants.is_none() { + return Err(format!( + "math metrics font {} has no OpenType MATH constants", + path.display() + )); + } + let units_per_em = f64::from(face.units_per_em()); + let x_height = face.x_height().filter(|value| *value > 0).or_else(|| { + face.glyph_index('x') + .and_then(|glyph| face.glyph_bounding_box(glyph)) + .map(|bounds| bounds.y_max) + .filter(|value| *value > 0) + }); + let math_alphanumeric_glyphs = if has_math_table { + math_alphanumeric_characters() + .filter(|character| face.glyph_index(*character).is_some()) + .collect() + } else { + HashSet::new() + }; + let font_bytes = has_math_table.then(|| Arc::<[u8]>::from(bytes)); + let glyph_fonts = [ + load_glyph_font(&glyph_font_paths[0])?, + load_glyph_font(&glyph_font_paths[1])?, + load_glyph_font(&glyph_font_paths[2])?, + load_glyph_font(&glyph_font_paths[3])?, + ]; + Ok(Self { + units_per_em, + x_height, + constants, + font_bytes, + math_alphanumeric_glyphs, + glyph_fonts, + custom_glyph_fonts: HashMap::new(), + math_glyph_cache: Arc::new(Mutex::new(HashMap::new())), + fingerprint, + }) + } + + fn cached_math_glyph_metrics( + &self, + bytes: &[u8], + character: char, + ) -> Option> { + let key = MathGlyphCacheKey { + font_bytes: bytes.as_ptr() as usize, + character, + }; + { + let cache = self + .math_glyph_cache + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(metrics) = cache.get(&key) { + return Some(Arc::clone(metrics)); + } + } + + let face = ttf_parser::Face::parse(bytes, 0).ok()?; + let glyph = face.glyph_index(character)?; + let glyph_info = face.tables().math?.glyph_info?; + let parsed = Arc::new(read_math_glyph_metrics(glyph_info, glyph)); + let mut cache = self + .math_glyph_cache + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + Some(Arc::clone(cache.entry(key).or_insert(parsed))) + } + + pub(super) fn has_math_alphanumeric_glyph(&self, character: char) -> bool { + self.math_alphanumeric_glyphs.contains(&character) + } + + pub(super) fn has_glyph_from_path(&self, path: &Path, character: char) -> bool { + self.custom_glyph_fonts + .get(path) + .is_some_and(|font| font.math_alphanumeric_glyphs.contains(&character)) + } + + pub(super) fn with_additional_glyph_fonts( + mut self, + paths: &HashSet, + ) -> Result { + let mut paths = paths.iter().collect::>(); + paths.sort(); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + self.fingerprint.hash(&mut hasher); + for path in paths { + let font = if let Some(font) = self.custom_glyph_fonts.get(path) { + font.clone() + } else { + load_glyph_font(path)? + }; + path.hash(&mut hasher); + font.bytes.hash(&mut hasher); + self.custom_glyph_fonts.insert(path.clone(), font); + } + self.fingerprint = hasher.finish(); + Ok(self) + } + + pub(super) fn rasterize_glyph_from_path( + &self, + path: &Path, + character: char, + font_size: u8, + ) -> Option { + let font = self.custom_glyph_fonts.get(path)?; + rasterize_math_glyph(&font.bytes, font.units_per_em, character, font_size) + } + + pub(super) fn italic_correction( + &self, + character: char, + style: Style, + prefer_math_font: bool, + ) -> Option { + let (bytes, units_per_em) = if prefer_math_font { + if let Some(bytes) = self.font_bytes.as_deref() { + (bytes, self.units_per_em) + } else { + let font = &self.glyph_fonts[glyph_font_index(style)]; + if !font.has_italic_corrections { + return None; + } + (&font.bytes[..], font.units_per_em) + } + } else { + let font = &self.glyph_fonts[glyph_font_index(style)]; + if !font.has_italic_corrections { + return None; + } + (&font.bytes[..], font.units_per_em) + }; + let glyph_metrics = self.cached_math_glyph_metrics(bytes, character)?; + let value = math_glyph::italic_correction(&glyph_metrics)?; + let millimeters_per_unit = f64::from(style.font_size()) * 25.4 + / (f64::from(super::PDF_POINTS_PER_INCH) * units_per_em); + Some(Mm::from(f64::from(value) * millimeters_per_unit)) + } + + pub(super) fn italic_correction_from_path( + &self, + path: &Path, + character: char, + style: Style, + ) -> Option { + let font = self.custom_glyph_fonts.get(path)?; + let glyph_metrics = self.cached_math_glyph_metrics(&font.bytes, character)?; + let value = math_glyph::italic_correction(&glyph_metrics)?; + let millimeters_per_unit = f64::from(style.font_size()) * 25.4 + / (f64::from(super::PDF_POINTS_PER_INCH) * font.units_per_em); + Some(Mm::from(f64::from(value) * millimeters_per_unit)) + } + + pub(super) fn glyph_italic_overhang( + &self, + character: char, + style: Style, + prefer_math_font: bool, + ) -> Option { + let (bytes, units_per_em) = if prefer_math_font { + self.font_bytes + .as_deref() + .map(|bytes| (bytes, self.units_per_em)) + .unwrap_or_else(|| { + let font = &self.glyph_fonts[glyph_font_index(style)]; + (&font.bytes[..], font.units_per_em) + }) + } else { + let font = &self.glyph_fonts[glyph_font_index(style)]; + (&font.bytes[..], font.units_per_em) + }; + if units_per_em <= 0.0 { + return None; + } + let face = ttf_parser::Face::parse(bytes, 0).ok()?; + let glyph = face.glyph_index(character)?; + let bounds = face.glyph_bounding_box(glyph)?; + let advance = face.glyph_hor_advance(glyph)?; + let overhang = (f64::from(bounds.x_max) - f64::from(advance)).max(0.0); + let millimeters_per_unit = f64::from(style.font_size()) * 25.4 + / (f64::from(super::PDF_POINTS_PER_INCH) * units_per_em); + Some(Mm::from(overhang * millimeters_per_unit)) + } + + pub(super) fn glyph_italic_overhang_from_path( + &self, + path: &Path, + character: char, + style: Style, + ) -> Option { + let font = self.custom_glyph_fonts.get(path)?; + let face = ttf_parser::Face::parse(&font.bytes, 0).ok()?; + let glyph = face.glyph_index(character)?; + let bounds = face.glyph_bounding_box(glyph)?; + let advance = face.glyph_hor_advance(glyph)?; + let overhang = (f64::from(bounds.x_max) - f64::from(advance)).max(0.0); + let millimeters_per_unit = f64::from(style.font_size()) * 25.4 + / (f64::from(super::PDF_POINTS_PER_INCH) * font.units_per_em); + Some(Mm::from(overhang * millimeters_per_unit)) + } + + pub(super) fn math_kern( + &self, + character: char, + style: Style, + prefer_math_font: bool, + corner: MathKernCorner, + correction_height: Mm, + ) -> Option { + let (bytes, units_per_em) = if prefer_math_font { + (self.font_bytes.as_deref()?, self.units_per_em) + } else { + let font = &self.glyph_fonts[glyph_font_index(style)]; + (&font.bytes[..], font.units_per_em) + }; + let glyph_metrics = self.cached_math_glyph_metrics(bytes, character)?; + let correction_height_units = + f64::from(correction_height) * PDF_POINTS_PER_INCH * units_per_em + / (f64::from(style.font_size()) * 25.4); + let value = + math_glyph::math_kern_at_height(&glyph_metrics, corner, correction_height_units)?; + let millimeters_per_unit = f64::from(style.font_size()) * 25.4 + / (f64::from(super::PDF_POINTS_PER_INCH) * units_per_em); + Some(Mm::from(f64::from(value) * millimeters_per_unit)) + } + + pub(super) fn math_kern_from_path( + &self, + path: &Path, + character: char, + style: Style, + corner: MathKernCorner, + correction_height: Mm, + ) -> Option { + let font = self.custom_glyph_fonts.get(path)?; + let glyph_metrics = self.cached_math_glyph_metrics(&font.bytes, character)?; + let correction_height_units = + f64::from(correction_height) * PDF_POINTS_PER_INCH * font.units_per_em + / (f64::from(style.font_size()) * 25.4); + let value = + math_glyph::math_kern_at_height(&glyph_metrics, corner, correction_height_units)?; + let millimeters_per_unit = f64::from(style.font_size()) * 25.4 + / (f64::from(super::PDF_POINTS_PER_INCH) * font.units_per_em); + Some(Mm::from(f64::from(value) * millimeters_per_unit)) + } + + pub(super) fn top_accent_attachment( + &self, + character: char, + style: Style, + prefer_math_font: bool, + ) -> Option { + let (bytes, units_per_em) = if prefer_math_font { + (self.font_bytes.as_deref()?, self.units_per_em) + } else { + let font = &self.glyph_fonts[glyph_font_index(style)]; + (&font.bytes[..], font.units_per_em) + }; + let glyph_metrics = self.cached_math_glyph_metrics(bytes, character)?; + let value = math_glyph::top_accent_attachment(&glyph_metrics)?; + let millimeters_per_unit = f64::from(style.font_size()) * 25.4 + / (f64::from(super::PDF_POINTS_PER_INCH) * units_per_em); + Some(Mm::from(f64::from(value) * millimeters_per_unit)) + } + + pub(super) fn top_accent_attachment_from_path( + &self, + path: &Path, + character: char, + style: Style, + ) -> Option { + let font = self.custom_glyph_fonts.get(path)?; + let glyph_metrics = self.cached_math_glyph_metrics(&font.bytes, character)?; + let value = math_glyph::top_accent_attachment(&glyph_metrics)?; + let millimeters_per_unit = f64::from(style.font_size()) * 25.4 + / (f64::from(super::PDF_POINTS_PER_INCH) * font.units_per_em); + Some(Mm::from(f64::from(value) * millimeters_per_unit)) + } + + pub(super) fn glyph_vertical_bounds( + &self, + character: char, + style: Style, + prefer_math_font: bool, + ) -> Option<(Mm, Mm)> { + if prefer_math_font { + let bytes = self.font_bytes.as_deref()?; + glyph_vertical_bounds_in_font(bytes, self.units_per_em, character, style) + } else { + let font = &self.glyph_fonts[glyph_font_index(style)]; + glyph_vertical_bounds_in_font(&font.bytes, font.units_per_em, character, style) + } + } + + pub(super) fn glyph_vertical_bounds_from_path( + &self, + path: &Path, + character: char, + style: Style, + ) -> Option<(Mm, Mm)> { + let font = self.custom_glyph_fonts.get(path)?; + glyph_vertical_bounds_in_font(&font.bytes, font.units_per_em, character, style) + } + + pub(super) fn rasterize_glyph( + &self, + character: char, + style: Style, + ) -> Option { + let font = &self.glyph_fonts[glyph_font_index(style)]; + rasterize_math_glyph(&font.bytes, font.units_per_em, character, style.font_size()).or_else( + || { + let bytes = self.font_bytes.as_deref()?; + rasterize_math_glyph(bytes, self.units_per_em, character, style.font_size()) + }, + ) + } + + pub(super) fn rasterize_math_symbol( + &self, + character: char, + font_size: u8, + ) -> Option { + let bytes = self.font_bytes.as_deref()?; + rasterize_math_glyph(bytes, self.units_per_em, character, font_size) + } + + pub(super) fn stretch_glyph( + &self, + delimiter: &str, + font_size: u8, + target_height: Mm, + ) -> Option { + self.stretch_glyph_on_axis( + delimiter, + font_size, + target_height, + StretchDirection::Vertical, + ) + } + + pub(super) fn stretch_glyph_from_path( + &self, + path: &Path, + glyph: &str, + font_size: u8, + target_height: Mm, + ) -> Option { + let font = self.custom_glyph_fonts.get(path)?; + Self::stretch_glyph_in_font( + &font.bytes, + font.units_per_em, + glyph, + font_size, + target_height, + StretchDirection::Vertical, + ) + } + + pub(super) fn stretch_horizontal_glyph_from_path( + &self, + path: &Path, + glyph: &str, + font_size: u8, + target_width: Mm, + ) -> Option { + let font = self.custom_glyph_fonts.get(path)?; + Self::stretch_glyph_in_font( + &font.bytes, + font.units_per_em, + glyph, + font_size, + target_width, + StretchDirection::Horizontal, + ) + } + + pub(super) fn stretch_horizontal_glyph( + &self, + glyph: &str, + font_size: u8, + target_width: Mm, + ) -> Option { + self.stretch_glyph_on_axis(glyph, font_size, target_width, StretchDirection::Horizontal) + } + + fn stretch_glyph_on_axis( + &self, + glyph: &str, + font_size: u8, + target_extent: Mm, + direction: StretchDirection, + ) -> Option { + Self::stretch_glyph_in_font( + self.font_bytes.as_deref()?, + self.units_per_em, + glyph, + font_size, + target_extent, + direction, + ) + } + + fn stretch_glyph_in_font( + bytes: &[u8], + units_per_em: f64, + glyph: &str, + font_size: u8, + target_extent: Mm, + direction: StretchDirection, + ) -> Option { + const MAX_DELIMITER_EM: f64 = 32.0; + const MAX_ASSEMBLY_PARTS: usize = 512; + const RASTER_DPI: f64 = 600.0; + + let glyph = glyph.chars().next()?; + if units_per_em <= 0.0 { + return None; + } + let face = ttf_parser::Face::parse(bytes, 0).ok()?; + let math = face.tables().math?; + let variants = math.variants?; + let glyph_id = face.glyph_index(glyph)?; + let constructions = match direction { + StretchDirection::Vertical => variants.vertical_constructions, + StretchDirection::Horizontal => variants.horizontal_constructions, + }; + let construction = constructions.get(glyph_id)?; + let font_size = f64::from(font_size.max(1)); + let millimeters_per_unit = + font_size * 25.4 / (f64::from(super::PDF_POINTS_PER_INCH) * units_per_em); + let requested_units = (f64::from(target_extent) / millimeters_per_unit) + .ceil() + .clamp(1.0, MAX_DELIMITER_EM * units_per_em); + + let mut largest_variant: Option = None; + let mut selected_variant = None; + for index in 0..construction.variants.len() { + let Some(variant) = construction.variants.get(index) else { + continue; + }; + if f64::from(variant.advance_measurement) >= requested_units { + selected_variant = Some(variant); + break; + } + if largest_variant + .is_none_or(|largest| variant.advance_measurement > largest.advance_measurement) + { + largest_variant = Some(variant); + } + } + let (parts, connector_overlaps, is_assembly) = if let Some(variant) = selected_variant { + let (parts, overlaps) = single_variant_parts(variant); + (parts, overlaps, false) + } else { + let assembled = construction.assembly.and_then(|assembly| { + let original_parts = assembly + .parts + .into_iter() + .map(StretchPart::from) + .collect::>(); + assemble_to_target( + original_parts, + variants.min_connector_overlap, + requested_units, + MAX_ASSEMBLY_PARTS, + ) + }); + if let Some(assembled) = assembled { + (assembled.0, assembled.1, true) + } else if let Some(variant) = largest_variant { + let (parts, overlaps) = single_variant_parts(variant); + (parts, overlaps, false) + } else { + return None; + } + }; + + rasterize_stretched_parts( + &face, + &parts, + &connector_overlaps, + millimeters_per_unit, + RASTER_DPI, + direction, + is_assembly, + ) + } + + pub(super) fn axis_height(&self, style: Style) -> Mm { + self.design_units(style, self.constants.map(|c| c.axis_height), 0.25) + } + + pub(super) fn axis_height_from_path(&self, path: &Path, style: Style) -> Option { + let font = self.custom_glyph_fonts.get(path)?; + let axis_height = font.constants?.axis_height; + Some(font_design_units(style, axis_height, font.units_per_em)) + } + + pub(super) fn accent_base_height(&self, style: Style) -> Mm { + if let Some(constants) = self.constants { + self.design_units(style, Some(constants.accent_base_height), 0.45) + } else { + self.glyph_vertical_bounds('x', style, false) + .map(|(top, _)| top) + .unwrap_or_else(|| self.em_fraction(style, 0.45)) + } + } + + pub(super) fn accent_base_height_from_path(&self, path: &Path, style: Style) -> Option { + let font = self.custom_glyph_fonts.get(path)?; + let face = ttf_parser::Face::parse(&font.bytes, 0).ok()?; + let value = face.tables().math?.constants?.accent_base_height().value; + let millimeters_per_unit = f64::from(style.font_size()) * 25.4 + / (f64::from(super::PDF_POINTS_PER_INCH) * font.units_per_em); + Some(Mm::from(f64::from(value) * millimeters_per_unit)) + } + + pub(super) fn display_operator_min_height(&self, style: Style) -> Mm { + self.design_units_unsigned( + style, + self.constants + .map(|constants| constants.display_operator_min_height), + 1.5, + ) + } + + pub(super) fn display_operator_target_height(&self, character: char, style: Style) -> Mm { + let minimum = self.display_operator_min_height(style); + let original_height = self + .glyph_vertical_bounds(character, style, true) + .map(|(top, bottom)| top - bottom) + .unwrap_or(Mm::from(0.0)); + minimum.max(original_height * 1.25) + } + + pub(super) fn display_operator_target_height_from_path( + &self, + path: &Path, + character: char, + style: Style, + ) -> Option { + let font = self.custom_glyph_fonts.get(path)?; + let minimum = font + .constants + .map(|constants| { + let font_size_mm = f64::from(style.font_size()) * 25.4 / PDF_POINTS_PER_INCH; + Mm::from( + font_size_mm * f64::from(constants.display_operator_min_height) + / font.units_per_em, + ) + }) + .unwrap_or_else(|| { + Mm::from(f64::from(style.font_size()) * 25.4 / PDF_POINTS_PER_INCH * 1.5) + }); + let original_height = + glyph_vertical_bounds_in_font(&font.bytes, font.units_per_em, character, style) + .map(|(top, bottom)| top - bottom) + .unwrap_or(Mm::from(0.0)); + Some(minimum.max(original_height * 1.25)) + } + + pub(super) fn fraction_metrics( + &self, + style: Style, + display_style: bool, + has_rule: bool, + ) -> MathFractionMetrics { + let parameters = + fraction_parameters(self.constants, self.units_per_em, display_style, has_rule); + fraction_metrics_from_parameters(style, self, parameters) + } + + pub(super) fn fraction_metrics_from_path( + &self, + path: &Path, + style: Style, + display_style: bool, + has_rule: bool, + ) -> Option { + let font = self.custom_glyph_fonts.get(path)?; + font.constants?; + let parameters = + fraction_parameters(font.constants, font.units_per_em, display_style, has_rule); + Some(fraction_metrics_from_parameters(style, self, parameters)) + } + + pub(super) fn radical_metrics(&self, style: Style, display_style: bool) -> (Mm, Mm, Mm) { + let parameters = radical_parameters( + self.constants, + self.units_per_em, + display_style, + self.x_height, + ); + ( + self.em_fraction(style, parameters.clearance), + self.em_fraction(style, parameters.rule_thickness), + self.em_fraction(style, parameters.extra_ascender), + ) + } + + pub(super) fn radical_metrics_from_path( + &self, + path: &Path, + style: Style, + display_style: bool, + ) -> Option<(Mm, Mm, Mm)> { + let font = self.custom_glyph_fonts.get(path)?; + let parameters = radical_parameters( + font.constants, + font.units_per_em, + display_style, + font.x_height, + ); + Some(( + self.em_fraction(style, parameters.clearance), + self.em_fraction(style, parameters.rule_thickness), + self.em_fraction(style, parameters.extra_ascender), + )) + } + + pub(super) fn overbar_metrics(&self, style: Style) -> (Mm, Mm, Mm) { + let parameters = overbar_parameters(self.constants, self.units_per_em); + ( + self.em_fraction(style, parameters.vertical_gap), + self.em_fraction(style, parameters.rule_thickness), + self.em_fraction(style, parameters.extra_extent), + ) + } + + pub(super) fn underbar_metrics(&self, style: Style) -> (Mm, Mm, Mm) { + let parameters = underbar_parameters(self.constants, self.units_per_em); + ( + self.em_fraction(style, parameters.vertical_gap), + self.em_fraction(style, parameters.rule_thickness), + self.em_fraction(style, parameters.extra_extent), + ) + } + + pub(super) fn overbar_metrics_from_path( + &self, + path: &Path, + style: Style, + ) -> Option<(Mm, Mm, Mm)> { + let font = self.custom_glyph_fonts.get(path)?; + font.constants?; + let parameters = overbar_parameters(font.constants, font.units_per_em); + Some(( + self.em_fraction(style, parameters.vertical_gap), + self.em_fraction(style, parameters.rule_thickness), + self.em_fraction(style, parameters.extra_extent), + )) + } + + pub(super) fn underbar_metrics_from_path( + &self, + path: &Path, + style: Style, + ) -> Option<(Mm, Mm, Mm)> { + let font = self.custom_glyph_fonts.get(path)?; + font.constants?; + let parameters = underbar_parameters(font.constants, font.units_per_em); + Some(( + self.em_fraction(style, parameters.vertical_gap), + self.em_fraction(style, parameters.rule_thickness), + self.em_fraction(style, parameters.extra_extent), + )) + } + + pub(super) fn radical_degree_metrics(&self, style: Style) -> (Mm, Mm, f64) { + let parameters = radical_degree_parameters(self.constants, self.units_per_em); + ( + self.em_fraction(style, parameters.kern_before_degree), + self.em_fraction(style, parameters.kern_after_degree), + parameters.bottom_raise_percent, + ) + } + + pub(super) fn radical_degree_metrics_from_path( + &self, + path: &Path, + style: Style, + ) -> Option<(Mm, Mm, f64)> { + let font = self.custom_glyph_fonts.get(path)?; + font.constants?; + let parameters = radical_degree_parameters(font.constants, font.units_per_em); + Some(( + self.em_fraction(style, parameters.kern_before_degree), + self.em_fraction(style, parameters.kern_after_degree), + parameters.bottom_raise_percent, + )) + } + + pub(super) fn style_for_math_style( + &self, + style: Style, + current: MathStyle, + target: MathStyle, + ) -> Style { + let script_percent = self + .constants + .map(|constants| constants.script_percent_scale_down) + .unwrap_or(70); + let scriptscript_percent = self + .constants + .map(|constants| constants.script_script_percent_scale_down) + .unwrap_or(49); + scale_math_style(style, current, target, script_percent, scriptscript_percent) + } + + pub(super) fn style_for_math_style_from_path( + &self, + path: &Path, + style: Style, + current: MathStyle, + target: MathStyle, + ) -> Option