Files
texrra-engine/README.md
T
gloamxun bb1d9e0561 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.
2026-10-19 11:41:46 +08:00

443 lines
24 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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 <http://127.0.0.1:4174>. 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/<id>` | Project metadata and file list |
| `DELETE /api/projects/<id>` | Delete a project |
| `GET /api/projects/<id>/zip` | Download the project as a ZIP |
| `GET /api/projects/<id>/raw?path=` | Read a file (`download=1` downloads it) |
| `PUT /api/projects/<id>/file?path=` | Write a text file |
| `POST /api/projects/<id>/files?path=` | Upload a file |
| `DELETE /api/projects/<id>/file?path=` | Delete a file |
| `POST /api/projects/<id>/preview` | Live preview of the main file |
| `POST /api/projects/<id>/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 `<div>` 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 `<class>.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.