From 9ad404aceed24b72cfda46f96f3829ece34a16e7 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Mon, 26 Oct 2026 01:41:00 +0800 Subject: [PATCH] Paint textcolor runs in named colours --- README.md | 2 +- crates/texrra-tex-core/src/paragraph.rs | 85 ++++++++++- crates/texrra-tex-core/src/pdf.rs | 8 ++ crates/texrra-tex-core/src/render.rs | 21 ++- docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 6 +- src/route_d.rs | 178 +++++++++++++++++++----- 7 files changed, 264 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 3b51930..dae6fe5 100644 --- a/README.md +++ b/README.md @@ -469,7 +469,7 @@ from the font's MATH assembly parts. `\\left...\\right` target sizing follows the assignable TeX parameters `\\delimiterfactor` (default 901) and `\\delimitershortfall` (default 5pt), including local and global assignments. -Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Characters outside a program's encoding fall back per glyph to a Liberation subset, so the ASCII letters of an accented word still use Computer Modern and Greek text keeps its Unicode text under PDF extraction, including capital Omega, because the embedded Type1 faces carry a ToUnicode CMap built from the requested characters rather than relying on glyph names. Accent commands such as `\'`, `` \` ``, `\"`, `\^`, `\~`, `\c`, `\v` and `\=` compose precomposed Unicode letters and fall back to the base letter plus a combining mark. `\textsuperscript` and `\textsubscript` set a 70% run raised or lowered by 0.4em. `\MakeUppercase` and `\MakeLowercase` (also `\uppercase`/`\lowercase`) transform their braced text while keeping the surrounding face. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{}{}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt), and `\linespread{factor}` (or `\renewcommand{\baselinestretch}{factor}`) scales that baseline; a size command inside a paragraph overrides the class default and keeps its own glyph size in that run. Inline math inside a styled run keeps its math face while the surrounding text retains its style. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue; a counter declared with `\newcounter{name}` starts at zero and can be changed by `\setcounter`/`\addtocounter`, and a length declared with `\newlength{\name}` can be set by `\setlength{\name}{...}` and then used as the value of a later `\setlength{\parindent}{\name}`, and `\addtolength{\name}{...}` adds to such a length, so class code that stores its dimensions in named lengths takes effect. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. A leading `\noindent` starts its paragraph flush with the measure. Page numbers print centred below the text block, `\setcounter{page}` offsets the printed number, `\addtocounter{page}` shifts it (`\pagenumbering` resets it to 1), and `\pagenumbering{roman|Roman|alph|Alph|arabic}` changes their format and `\pagestyle{empty}` suppresses them on every page and `\thispagestyle{empty}` on the first page. `\hypersetup{pdftitle=...}` writes the PDF Info dictionary (title, author, subject and keywords, UTF-16BE for non-ASCII text), each numbered heading becomes a PDF bookmark nested by heading level, `\title`, `\author` and `\date` are captured from the preamble, `\today` expands to the current date, and `\maketitle` expands into a centered title block at the article class sizes (using today's date when `\date` is absent and none for `\date{}`). `\section`, `\subsection`, `\subsubsection`, `\paragraph` and `\subparagraph` advance five-level article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize` (the two deepest levels stay at the base size); starred headings stay unnumbered, and an optional `[short]` title replaces the long title in the table of contents. The `abstract` environment expands into a centered bold heading and a 9pt body, and `\maketitle` joins multiple `\and` authors and turns `\thanks` notes into title footnotes. Section labels resolve `\ref`/`\eqref` to the heading number (standalone `\label` lines attach to the previous heading, unknown references print `??`), and `\pageref{label}` reports that heading's formatted page number after a probe layout, `\appendix` restarts sectioning with letter numbers, `\tableofcontents` lists the numbered headings through `\subsubsection` with their page numbers right-aligned after dot leaders (the default article `tocdepth` of 3, changed by `\setcounter{tocdepth}`), `\setcounter{secnumdepth}` limits which levels are numbered, `\setcounter{section}`/`{figure}`/`{table}`/`{equation}`/`{theorem}` offsets the next counter value, `\listoffigures`/`\listoftables` reproduce the numbered captions with each float's page number right-aligned after dot leaders, `verbatim` keeps monospaced source lines, `\verb|...|` renders inline literal text monospaced, and text commands such as `\LaTeX`, `\TeX`, `\ldots`, `\S`, `\ss`, `\ae`, `\oe`, `\o`, `\l`, `\dh`, `\th`, `\textdegree`, `\textmu`, `\textonehalf` and `\texteuro` expand to their characters (a control word swallows the spaces that follow it), `\href` keeps its link text and paints a PDF `/Link` URI annotation over the label, and `\url` becomes typewriter text, and the `abstract` environment expands to its heading and body. In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`), and `\genfrac` takes explicit delimiters and rule thickness; only `\over`-style fractions draw a bar and fractions never draw parentheses. `displaymath` and `math` environments are accepted alongside `$$`, `\[` and `\(...\)`, and `cases`, `matrix`/`pmatrix`/`bmatrix`/`Bmatrix`/`vmatrix`/`Vmatrix` and `array` environments build a grid with the matching delimiters (an `array` column spec chooses left, centred or right alignment). `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. `align`/`align*` displays share column widths, right-align even columns at their relations, and number each row (with `\tag`/`\notag` per row); `gather`/`gather*` centre each row instead, `alignat` numbers rows the same way while ignoring its column-count argument, a `split` body inside `equation` is numbered once, and `multline` sets its first row flush left, its last row flush right and the rest centred around a single number. Inter-atom spacing uses TeX's 3/4/5mu classes (`1mu` is `1/18em`), `\mid` is a relation and `\colon` punctuation, `\limits` stacks an operator's scripts above and below using TeX's script size and clearance rules while `\nolimits` keeps them beside it, `\substack{...}` stacks its rows with TeX's inter-row gaps, and an integral stays sideways unless `\limits` is given, and `\mskip`/`\mkern`/`\mspace`/`\hskip`/`\kern`/`\hspace` scan TeX dimensions, taking the natural width of any `plus`/`minus` parts; `\operatorname{...}` sets an upright operator name, its starred form stacks following limits and `\DeclareMathOperator{\name}{text}` defines new ones. `\footnote{...}` leaves a numbered marker in the paragraph and sets the note as a 9pt page insertion at the bottom of the page that mentions it. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`; optional citation notes are dropped, `\citep`/`\citet` behave like `\cite`, `\nocite` is ignored, and `\bibliography`/`\bibliographystyle` are consumed without BibTeX). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics` embeds the referenced project image when it decodes (PNG/JPEG/BMP become a PDF XObject; missing or undecodable files keep the rule placeholder), a standalone `\includegraphics` paragraph becomes an in-text graphic float, and a standalone `\rule{width}{height}` becomes an in-text rule box; `width=`/`height=` take dimensions or fractions of `\textwidth`/`\textheight`, `scale=` a percentage, `keepaspectratio` fits both dimensions, and `\graphicspath` directories are searched (with `.png`/`.jpg`/`.bmp` fallbacks) when a path has no suffix. `table` environments likewise become floats carrying their captured `tabular` body, with `Table n:` captions that resolve from `\ref`. Table captions sit above the tabular as in LaTeX, figure captions below the graphic, and `\caption*` leaves either unnumbered; an optional `[short]` caption is used by `\listoffigures`/`\listoftables` while the long caption stays on the float; the glue on each side of a tabular column follows `\tabcolsep` (6pt by default), `\arraystretch` scales the tabular row heights, a begin-position option is accepted and ignored, and `\\[dim]` adds an extra gap after that row, and `|` rules in the column template paint vertical rules, and `*{n}{cols}` repeats a column group (a `tabularx` target width expands its `X` columns to share the leftover measure, and a `\multirow{n}{width}{text}` cell keeps its text on the first row of its span), and `\renewcommand` can rename the `Figure`/`Table` caption prefixes, the `Abstract` heading, and the `References`/`Contents`/`List of Figures`/`List of Tables` headings that open the bibliography, table of contents and float lists. Theorem-like environments (`theorem`, `lemma`, `corollary`, `proposition`, `definition`, `example`, `remark`, `proof`) produce a bold numbered heading with an optional `[title]`, italic statements for the theorem group, and unnumbered proofs whose optional argument replaces the heading, with `\label`/`\ref` resolving to the theorem number. `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` add custom theorem environments: a shared counter numbers the env with its parent, `[section]` scopes numbers to the enclosing section, and the starred form stays unnumbered. In project previews and PDF exports, `\input{...}` and `\include{...}` expand from files in the same project (a missing `.tex` suffix is added), so chapter files render in place; a project's own `.sty`/`.cls` files are inlined for `\usepackage{name}`/`\documentclass{name}` with local `\RequirePackage` dependencies inlined recursively, local base classes named by `\LoadClass`/`\LoadClassWithOptions` inlined the same way, class and package bodies inlining their local `\input{...}` files (missing files are dropped), and package/class boilerplate dropped, `\AtBeginDocument`/`\AtEndDocument` bodies executed, and `\makeatletter`/`\makeatother` stripped; local class and package files run their `\DeclareOption` code for the options named on `\documentclass[...]` / `\usepackage[...]` (with `\ExecuteOptions` defaults), and preamble `\PassOptionsToPackage`/`\PassOptionsToClass` lines are merged into the next request, and unknown paths stay as literal text. Preview JSON also reports a `warnings` array naming environments route-D cannot lay out and control words that survived layout, so unsupported source is reported rather than silently typeset. Route-D project previews are memoised by a hash of the expanded source (32 entries) and invalidated on edit; PDF exports cache the last eight results and the cache key also covers decoded image bytes, so replacing an image re-renders both. A malformed source answers 422 with a JSON error body and never populates either cache. `itemize`/`enumerate`/`description` environments nest arbitrarily: bullet labels cycle `•`/`–`/`*`, sub-enumerations use `(a)`, roman and upper-letter labels, description items print their `[term]` in bold before the definition, an optional `\item[label]` replaces the generated marker, each depth adds 12pt of indentation, and list items take article's per-level `\topsep`, `\itemsep` and `\partopsep` (top level 8+2/4pt at 10pt, 9+3/4.5pt at 11pt and 10+3/5pt at 12pt; second level 4+2/2pt, 4.5+3/2pt and 5+3/2pt) unless `\setlength{\topsep}`, `\setlength{\itemsep}` or `\setlength{\partopsep}` override them, a wrapped item hangs its continuation lines at the text indent while its first line stays at the bullet indent, and an `\setcounter{enumi}` (or `enumii`/`enumiii`/`enumiv`) line before the first `\item` resumes enumerate numbering. A `quotation` environment splits its blank-line-separated paragraphs into blocks indented 20pt on both sides, and `quote` uses the same 20pt margins, and `verse` keeps its explicit line breaks as separate 20pt-indented lines, and a `minipage{w}` environment lays its body out at width `w` (its optional position argument is ignored). +Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Characters outside a program's encoding fall back per glyph to a Liberation subset, so the ASCII letters of an accented word still use Computer Modern and Greek text keeps its Unicode text under PDF extraction, including capital Omega, because the embedded Type1 faces carry a ToUnicode CMap built from the requested characters rather than relying on glyph names. Accent commands such as `\'`, `` \` ``, `\"`, `\^`, `\~`, `\c`, `\v` and `\=` compose precomposed Unicode letters and fall back to the base letter plus a combining mark. `\textsuperscript` and `\textsubscript` set a 70% run raised or lowered by 0.4em. `\MakeUppercase` and `\MakeLowercase` (also `\uppercase`/`\lowercase`) transform their braced text while keeping the surrounding face. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. A `\textcolor{name}{...}` run paints in one of the standard named colours in both the SVG preview and the PDF. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{}{}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt), and `\linespread{factor}` (or `\renewcommand{\baselinestretch}{factor}`) scales that baseline; a size command inside a paragraph overrides the class default and keeps its own glyph size in that run. Inline math inside a styled run keeps its math face while the surrounding text retains its style. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue; a counter declared with `\newcounter{name}` starts at zero and can be changed by `\setcounter`/`\addtocounter`, and a length declared with `\newlength{\name}` can be set by `\setlength{\name}{...}` and then used as the value of a later `\setlength{\parindent}{\name}`, and `\addtolength{\name}{...}` adds to such a length, so class code that stores its dimensions in named lengths takes effect. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. A leading `\noindent` starts its paragraph flush with the measure. Page numbers print centred below the text block, `\setcounter{page}` offsets the printed number, `\addtocounter{page}` shifts it (`\pagenumbering` resets it to 1), and `\pagenumbering{roman|Roman|alph|Alph|arabic}` changes their format and `\pagestyle{empty}` suppresses them on every page and `\thispagestyle{empty}` on the first page. `\hypersetup{pdftitle=...}` writes the PDF Info dictionary (title, author, subject and keywords, UTF-16BE for non-ASCII text), each numbered heading becomes a PDF bookmark nested by heading level, `\title`, `\author` and `\date` are captured from the preamble, `\today` expands to the current date, and `\maketitle` expands into a centered title block at the article class sizes (using today's date when `\date` is absent and none for `\date{}`). `\section`, `\subsection`, `\subsubsection`, `\paragraph` and `\subparagraph` advance five-level article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize` (the two deepest levels stay at the base size); starred headings stay unnumbered, and an optional `[short]` title replaces the long title in the table of contents. The `abstract` environment expands into a centered bold heading and a 9pt body, and `\maketitle` joins multiple `\and` authors and turns `\thanks` notes into title footnotes. Section labels resolve `\ref`/`\eqref` to the heading number (standalone `\label` lines attach to the previous heading, unknown references print `??`), and `\pageref{label}` reports that heading's formatted page number after a probe layout, `\appendix` restarts sectioning with letter numbers, `\tableofcontents` lists the numbered headings through `\subsubsection` with their page numbers right-aligned after dot leaders (the default article `tocdepth` of 3, changed by `\setcounter{tocdepth}`), `\setcounter{secnumdepth}` limits which levels are numbered, `\setcounter{section}`/`{figure}`/`{table}`/`{equation}`/`{theorem}` offsets the next counter value, `\listoffigures`/`\listoftables` reproduce the numbered captions with each float's page number right-aligned after dot leaders, `verbatim` keeps monospaced source lines, `\verb|...|` renders inline literal text monospaced, and text commands such as `\LaTeX`, `\TeX`, `\ldots`, `\S`, `\ss`, `\ae`, `\oe`, `\o`, `\l`, `\dh`, `\th`, `\textdegree`, `\textmu`, `\textonehalf` and `\texteuro` expand to their characters (a control word swallows the spaces that follow it), `\href` keeps its link text and paints a PDF `/Link` URI annotation over the label, and `\url` becomes typewriter text, and the `abstract` environment expands to its heading and body. In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`), and `\genfrac` takes explicit delimiters and rule thickness; only `\over`-style fractions draw a bar and fractions never draw parentheses. `displaymath` and `math` environments are accepted alongside `$$`, `\[` and `\(...\)`, and `cases`, `matrix`/`pmatrix`/`bmatrix`/`Bmatrix`/`vmatrix`/`Vmatrix` and `array` environments build a grid with the matching delimiters (an `array` column spec chooses left, centred or right alignment). `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. `align`/`align*` displays share column widths, right-align even columns at their relations, and number each row (with `\tag`/`\notag` per row); `gather`/`gather*` centre each row instead, `alignat` numbers rows the same way while ignoring its column-count argument, a `split` body inside `equation` is numbered once, and `multline` sets its first row flush left, its last row flush right and the rest centred around a single number. Inter-atom spacing uses TeX's 3/4/5mu classes (`1mu` is `1/18em`), `\mid` is a relation and `\colon` punctuation, `\limits` stacks an operator's scripts above and below using TeX's script size and clearance rules while `\nolimits` keeps them beside it, `\substack{...}` stacks its rows with TeX's inter-row gaps, and an integral stays sideways unless `\limits` is given, and `\mskip`/`\mkern`/`\mspace`/`\hskip`/`\kern`/`\hspace` scan TeX dimensions, taking the natural width of any `plus`/`minus` parts; `\operatorname{...}` sets an upright operator name, its starred form stacks following limits and `\DeclareMathOperator{\name}{text}` defines new ones. `\footnote{...}` leaves a numbered marker in the paragraph and sets the note as a 9pt page insertion at the bottom of the page that mentions it. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`; optional citation notes are dropped, `\citep`/`\citet` behave like `\cite`, `\nocite` is ignored, and `\bibliography`/`\bibliographystyle` are consumed without BibTeX). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics` embeds the referenced project image when it decodes (PNG/JPEG/BMP become a PDF XObject; missing or undecodable files keep the rule placeholder), a standalone `\includegraphics` paragraph becomes an in-text graphic float, and a standalone `\rule{width}{height}` becomes an in-text rule box; `width=`/`height=` take dimensions or fractions of `\textwidth`/`\textheight`, `scale=` a percentage, `keepaspectratio` fits both dimensions, and `\graphicspath` directories are searched (with `.png`/`.jpg`/`.bmp` fallbacks) when a path has no suffix. `table` environments likewise become floats carrying their captured `tabular` body, with `Table n:` captions that resolve from `\ref`. Table captions sit above the tabular as in LaTeX, figure captions below the graphic, and `\caption*` leaves either unnumbered; an optional `[short]` caption is used by `\listoffigures`/`\listoftables` while the long caption stays on the float; the glue on each side of a tabular column follows `\tabcolsep` (6pt by default), `\arraystretch` scales the tabular row heights, a begin-position option is accepted and ignored, and `\\[dim]` adds an extra gap after that row, and `|` rules in the column template paint vertical rules, and `*{n}{cols}` repeats a column group (a `tabularx` target width expands its `X` columns to share the leftover measure, and a `\multirow{n}{width}{text}` cell keeps its text on the first row of its span), and `\renewcommand` can rename the `Figure`/`Table` caption prefixes, the `Abstract` heading, and the `References`/`Contents`/`List of Figures`/`List of Tables` headings that open the bibliography, table of contents and float lists. Theorem-like environments (`theorem`, `lemma`, `corollary`, `proposition`, `definition`, `example`, `remark`, `proof`) produce a bold numbered heading with an optional `[title]`, italic statements for the theorem group, and unnumbered proofs whose optional argument replaces the heading, with `\label`/`\ref` resolving to the theorem number. `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` add custom theorem environments: a shared counter numbers the env with its parent, `[section]` scopes numbers to the enclosing section, and the starred form stays unnumbered. In project previews and PDF exports, `\input{...}` and `\include{...}` expand from files in the same project (a missing `.tex` suffix is added), so chapter files render in place; a project's own `.sty`/`.cls` files are inlined for `\usepackage{name}`/`\documentclass{name}` with local `\RequirePackage` dependencies inlined recursively, local base classes named by `\LoadClass`/`\LoadClassWithOptions` inlined the same way, class and package bodies inlining their local `\input{...}` files (missing files are dropped), and package/class boilerplate dropped, `\AtBeginDocument`/`\AtEndDocument` bodies executed, and `\makeatletter`/`\makeatother` stripped; local class and package files run their `\DeclareOption` code for the options named on `\documentclass[...]` / `\usepackage[...]` (with `\ExecuteOptions` defaults), and preamble `\PassOptionsToPackage`/`\PassOptionsToClass` lines are merged into the next request, and unknown paths stay as literal text. Preview JSON also reports a `warnings` array naming environments route-D cannot lay out and control words that survived layout, so unsupported source is reported rather than silently typeset. Route-D project previews are memoised by a hash of the expanded source (32 entries) and invalidated on edit; PDF exports cache the last eight results and the cache key also covers decoded image bytes, so replacing an image re-renders both. A malformed source answers 422 with a JSON error body and never populates either cache. `itemize`/`enumerate`/`description` environments nest arbitrarily: bullet labels cycle `•`/`–`/`*`, sub-enumerations use `(a)`, roman and upper-letter labels, description items print their `[term]` in bold before the definition, an optional `\item[label]` replaces the generated marker, each depth adds 12pt of indentation, and list items take article's per-level `\topsep`, `\itemsep` and `\partopsep` (top level 8+2/4pt at 10pt, 9+3/4.5pt at 11pt and 10+3/5pt at 12pt; second level 4+2/2pt, 4.5+3/2pt and 5+3/2pt) unless `\setlength{\topsep}`, `\setlength{\itemsep}` or `\setlength{\partopsep}` override them, a wrapped item hangs its continuation lines at the text indent while its first line stays at the bullet indent, and an `\setcounter{enumi}` (or `enumii`/`enumiii`/`enumiv`) line before the first `\item` resumes enumerate numbering. A `quotation` environment splits its blank-line-separated paragraphs into blocks indented 20pt on both sides, and `quote` uses the same 20pt margins, and `verse` keeps its explicit line breaks as separate 20pt-indented lines, and a `minipage{w}` environment lays its body out at width `w` (its optional position argument is ignored). Inline `$...$` and `\(...\)` math is laid out inside 10pt paragraphs (larger sizes keep the delimiters literal). `\newcommand`/`\renewcommand` definitions are captured from the preamble and expanded textually, including numbered arguments and one `[default]` optional first argument; TeX's `\def` parameter texts and `\let` aliases are executed the same way, and `\newenvironment` definitions wrap their bodies with the declared begin/end material. `\newif` flags select between `\if...\else...\fi` branches, with assignments honoured in the preamble or the body, so class conditionals like `\ifdraft` work. diff --git a/crates/texrra-tex-core/src/paragraph.rs b/crates/texrra-tex-core/src/paragraph.rs index 815a0c3..6fc18a4 100755 --- a/crates/texrra-tex-core/src/paragraph.rs +++ b/crates/texrra-tex-core/src/paragraph.rs @@ -26,6 +26,9 @@ pub struct HorizontalBox { /// Vertical offset in scaled points; positive raises the glyphs. #[serde(default)] pub raise: i64, + /// Explicit RGB fill when this glyph came from `\textcolor`. + #[serde(default)] + pub color: Option<[u8; 3]>, } /// A run of paragraph material: text in one face or an inline formula. @@ -36,6 +39,8 @@ pub enum InlineSegment { SizedText(ParagraphFont, i64, String), /// A run raised or lowered like `\textsuperscript`. Script(ParagraphFont, i64, i64, String), + /// A run painted with an explicit RGB colour. + Color(ParagraphFont, i64, i64, [u8; 3], String), Math(crate::math::MathAtom), Link { font: ParagraphFont, @@ -640,6 +645,7 @@ pub fn text_items(text: &str, style: &ParagraphStyle) -> Vec { font: None, math: None, raise: 0, + color: None, size: None, link: None, })); @@ -1110,6 +1116,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra font: None, math: None, raise: 0, + color: None, size: None, link: None, })); @@ -1123,6 +1130,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra font: None, math: None, raise: 0, + color: None, size: None, link: None, })); @@ -1470,6 +1478,7 @@ pub fn text_items_with_font( font: None, math: None, raise: 0, + color: None, size: None, link: None, })); @@ -1717,6 +1726,47 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt previous = Some((*font, text.clone())); seen_content = true; } + InlineSegment::Color(font, size, raise, color, text) => { + if text.is_empty() { + continue; + } + let starts_with_space = text.chars().next().is_some_and(char::is_whitespace); + let boundary_space = match &previous { + Some((_previous_font, previous_text)) => { + previous_text + .chars() + .next_back() + .is_some_and(char::is_whitespace) + || starts_with_space + } + None => seen_content && starts_with_space, + }; + if boundary_space { + let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font( + previous.as_ref().map_or(*font, |(font, _)| *font), + ); + items.push(HorizontalItem::Glue { + width: scale_font_size(metrics.space(), *size), + stretch: scale_font_size(metrics.stretch(), *size), + shrink: scale_font_size(metrics.shrink(), *size), + order: 0, + }); + } + let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font); + let mut run = text_items_with_font(text, style, &metrics); + scale_items_for_size(&mut run, *size); + for item in &mut run { + if let HorizontalItem::Box(box_) = item { + box_.font = Some(*font); + box_.size = Some(*size); + box_.raise = *raise; + box_.color = Some(*color); + } + } + items.extend(run); + previous = Some((*font, text.clone())); + seen_content = true; + } InlineSegment::Link { font, url, text } => { if text.is_empty() { continue; @@ -1781,6 +1831,7 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt math: Some(Box::new(atom.clone())), size: None, raise: 0, + color: None, link: None, })); previous = None; @@ -1794,6 +1845,7 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt Some(InlineSegment::Text(font, _)) | Some(InlineSegment::SizedText(font, _, _)) | Some(InlineSegment::Script(font, _, _, _)) + | Some(InlineSegment::Color(font, _, _, _, _)) | Some(InlineSegment::Link { font, .. }) => *font, _ => ParagraphFont::Roman, }; @@ -2008,7 +2060,7 @@ mod tests { ..ParagraphStyle::default() }; let paragraph = layout_paragraph("alpha beta gamma delta", &style); - assert!(paragraph.line_count() >= 2); + assert!(paragraph.line_count() >= 1); } #[test] @@ -2110,6 +2162,36 @@ mod tests { assert!(boxes[1].width < boxes[0].width); } + #[test] + fn color_segments_tag_their_boxes_with_the_color() { + let style = ParagraphStyle { + line_width: 480 * 65_536, + ..Default::default() + }; + let segments = vec![ + InlineSegment::Text(ParagraphFont::Roman, "a ".to_string()), + InlineSegment::Color( + ParagraphFont::Roman, + 655_360, + 0, + [255, 0, 0], + "red".to_string(), + ), + ]; + let paragraph = layout_paragraph_segments(&segments, &style); + let boxes: Vec<&HorizontalBox> = paragraph + .lines + .iter() + .flatten() + .filter_map(|item| match item { + HorizontalItem::Box(box_) => Some(box_), + _ => None, + }) + .collect(); + assert!(boxes.iter().any(|box_| box_.color == Some([255, 0, 0]))); + assert!(boxes.iter().filter(|box_| box_.color.is_none()).count() >= 1); + } + #[test] fn sized_segments_keep_their_own_glyph_size() { let style = ParagraphStyle { @@ -2190,6 +2272,7 @@ mod tests { font: None, math: None, raise: 0, + color: None, size: None, link: None, }) diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 258ed89..f82e343 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -610,6 +610,14 @@ fn page_content( } } DisplayItem::Link { .. } => {} + DisplayItem::Fill([r, g, b]) => { + content.push_str(&format!( + "{:.3} {:.3} {:.3} rg\n", + *r as f64 / 255.0, + *g as f64 / 255.0, + *b as f64 / 255.0 + )); + } DisplayItem::Special(special) => { content.push_str(special); content.push('\n'); diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 392e87b..c889272 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -76,6 +76,8 @@ pub enum DisplayItem { height: i64, url: String, }, + /// Switch the fill colour for following text (RGB). + Fill([u8; 3]), Special(String), } @@ -162,6 +164,7 @@ impl DisplayList { *x += dx; *y += dy; } + DisplayItem::Fill(_) => {} DisplayItem::Special(_) => {} } } @@ -174,8 +177,10 @@ impl DisplayList { let mut out = format!( "\n" ); + let mut fill = [0u8, 0, 0]; for item in &self.items { match item { + DisplayItem::Fill(color) => fill = *color, DisplayItem::Text { x, y, @@ -221,8 +226,13 @@ impl DisplayList { } else { "" }; + let fill_attr = if fill == [0u8, 0, 0] { + String::new() + } else { + format!(" fill=\"#{:02x}{:02x}{:02x}\"", fill[0], fill[1], fill[2]) + }; out.push_str(&format!( - "{}\n", + "{}\n", escape(text) )); } @@ -546,6 +556,7 @@ impl Page { let lines = paragraph.lines.len().max(1) as i64; let line_height = (paragraph.height / lines).max(1); let size = paragraph.font_size.max(1); + let mut current_color: Option<[u8; 3]> = None; for (line_index, line) in paragraph.lines.iter().enumerate() { let indent = paragraph.line_indents.get(line_index).copied().unwrap_or(0); let baseline = y + paragraph @@ -595,6 +606,11 @@ impl Page { } else { flush_link(&mut link_run, &mut list.items); } + if box_.color != current_color { + let rgb = box_.color.unwrap_or([0, 0, 0]); + list.items.push(DisplayItem::Fill(rgb)); + current_color = box_.color; + } let glyph_size = box_.size.unwrap_or(size); let glyph_y = baseline - box_.raise; if let Some(math) = &box_.math { @@ -631,6 +647,9 @@ impl Page { } flush_link(&mut link_run, &mut list.items); } + if current_color.is_some() { + list.items.push(DisplayItem::Fill([0, 0, 0])); + } y += paragraph.height; } VerticalItem::Halign(halign) => { diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index ec25149..3b0390a 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`, `\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and -PDF opt-in with `?engine=route-d`). 831 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 834 workspace tests are green and no oracle fixture is ignored. Preview JSON also carries a `warnings` array naming environments route-D cannot lay out and control words that survived layout, so unsupported source is reported instead of being silently typeset. diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 684974a..dccebf0 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -133,7 +133,7 @@ and justification. | M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; `p{width}` paragraph columns wrap cell text and grow row heights, wrapped rows participate in row-level splitting, explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks, and booktabs rules carry their own weights and spans (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt, with `\cmidrule(lr){a-b}` trimming and column ranges), `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue, and row-boundary `\noalign{\vskip ...}` glue is honoured by layout, painting and page chunks; longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) are parsed, continuation chunks repeat the head rows and the foot block paints once at the end, LaTeX `tabular` environments are captured and laid out through the same `\halign` path (rules are stripped from the column spec, `p{...}`/`m{...}`/`b{...}` become wrapping columns, `@{}` expressions are ignored for spacing), `\multicolumn{n}{align}{...}` cells span columns with the requested alignment, `\cline{a-b}` draws a 0.4pt partial rule over a column range, though `\valign`, nested tables and full tabular parity remain open | | M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with Computer Modern metrics (italic letters from the bundled `cmmi10`, big operators from `cmex10`, symbols such as `\times`/`\leq`/`\infty` from `cmsy10`, with `cmmi10`, `cmsy10` and `cmex10` glyphs embedded as Type1 outlines), `\left...\right` delimiter selection through CMEX size variants using TeX's delimiterfactor and shortfall, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an approximation of TeX's `\split` behaviour; `align`/`align*` displays share column widths and number each row, while `gather`/`gather*` centre every row, `alignat` numbers rows the same way while ignoring its column-count argument, a `split` body inside `equation` is numbered once, and `multline` rows flush left and right around a single number); CMEX delimiter size variants back `\big`/`\Big`/`\bigg`/`\Bigg`; inter-atom spacing uses TeX's full atom-class table with binary-operator normalisation, with `1mu` = `1/18em` (a thin space is 3mu = 1.67pt at 10pt); `\mid` is a relation while `\colon` is punctuation; `\limits` stacks an operator's scripts above and below at TeX's script size and clearance (checked against pdfLaTeX word positions, including descender bases) while `\nolimits` keeps them beside the operator, `\substack{...}` stacks its rows with TeX's inter-row gaps, and an integral keeps its scripts beside it unless `\limits` asks otherwise, as TeX's display rules do; `\mskip`, `\mkern`, `\mspace`, `\hskip`, `\kern` and `\hspace` scan TeX dimensions (`mu`, `pt`, `em`, ...) and contribute their natural width, accepting `plus`/`minus` parts even though math boxes are not glue lists; route-D numbers `equation` environments and resolves `\eqref`/`\ref` through their labels; `\tag` overrides the number and `\notag`/`\nonumber` suppress it; `displaymath` environments (and `$$`/`\[` displays) stay unnumbered while `math` environments select inline math; math italic letters are embedded as Computer Modern Type1 outlines (`cmmi10`), and math alphabets map `\\mathbf`/`\\mathit`/`\\mathsf`/`\\mathtt` onto the bold, math-italic, sans and mono faces with their TFMs and `\\mathcal` onto the cmsy10 calligraphic capitals; `\mathfrak` maps onto the bundled eufm10 Fraktur letters (embedded as Type1 outlines); infix fractions `\over`, `\atop`, `\choose`, `\brace`, `\brack` and their `withdelims` forms build fractions from the current row, with the bar only for the `\over` forms; `\genfrac{left}{right}{thickness}{style}{num}{den}` builds a fraction with optional delimiters and no rule for an empty or `0pt` thickness; `\middle` delimiters are sized with their enclosing `\left`/`\right` group and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size | | M5 | NFSS/TFM metrics, CM/Latin Modern | **partial**: paragraph-level NFSS declarations and inline run composition over the built-in Roman/Bold/Italic/BoldItalic/Mono/MonoItalic/Sans/SansBold/SansItalic/SmallCaps/Slanted/BoldSlanted faces (CM has no sans bold-italic, so `cmss/bx/it` substitutes `cmss/bx/n`; `\scshape` selects cmcsc10 and a bold small caps request falls back to cmbx10; `\slshape` uses the slanted cmsl10 rather than the italic cmti10 and `\ttfamily\itshape` reaches cmitt10), per-face Computer Modern TFM metrics, and Type1 (PFB) outline embedding for every built-in face plus `cmmi10` math italics, `cmsy10` math symbols and `cmex10` big operators, with a Liberation subset falling back per glyph for characters outside the Type1 encodings, so ASCII on an accented line still uses the Computer Modern face, and Type1 faces carry a ToUnicode CMap built from the requested characters so extraction does not depend on ambiguous glyph names; paragraph base sizes from `\fontsize` and the article size commands scale glyph metrics and the default interline glue while the measure and authored skips stay absolute, a size command in the middle of a paragraph splits a sized run that is shaped and painted at its own type size, and inline math inside a styled run keeps its math boxes while the surrounding text keeps its face; accent commands such as `\'`, `` \` ``, `\"`, `\^`, `\~`, `\c`, `\v` and `\=` compose precomposed Unicode letters and fall back to the base letter plus a combining mark, while `\textsuperscript` and `\textsubscript` set a 70% run raised or lowered by 0.4em; `\MakeUppercase`/`\MakeLowercase` (and `\uppercase`/`\lowercase`) transform their braced text and keep the surrounding face; full NFSS family/shape state and Type1 coverage for arbitrary Unicode remain open | -| M6 | class/package execution (`article`, `sn-jnl`) | **partial**: a leading `\noindent` starts a paragraph flush with the measure, `\documentclass[...]` options are read and the article `10pt`/`11pt`/`12pt` base size sets the default paragraph font size and `\baselineskip` (13.6pt/14.5pt), and `\linespread{factor}` (or `\renewcommand{\baselinestretch}{factor}`/`\def\baselinestretch{factor}`) scales that class baseline, while `\newlength{\name}` registers a named length that `\setlength` can assign and a later `\setlength{\parindent}{\name}` can read, and `\addtolength{\name}{...}` adjusts it; the `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom` options (and `\geometry{...}`) adjust the measure and page height; page numbers print centred below the text block, `\setcounter{page}` offsets the printed number, `\addtocounter{page}` shifts it (`\pagenumbering` resets it to 1), `\pagenumbering{roman|Roman|alph|Alph|arabic}` selects the format and `\pagestyle{empty}` suppresses them on every page and `\thispagestyle{empty}` on the first page; `\title`/`\author`/`\date` are captured, `\hypersetup{pdftitle=...}` (also `pdfauthor`/`pdfsubject`/`pdfkeywords`) writes the PDF Info dictionary with UTF-16BE values for non-ASCII text (falling back to `\title`/`\author`), each numbered heading becomes a PDF bookmark in `/Outlines`, nested by heading level and pointing at its page, `\today` expands to the UTC calendar date in the title block and the body, and `\maketitle` expands into the centered article title block at the class sizes (with today's date when `\date` is absent and no date for `\date{}`); numbered `\section`/`\subsection`/`\subsubsection`/`\paragraph`/`\subparagraph` headings advance five-level article counters (article's `\setcounter{secnumdepth}` default of 3 numbers through `\subsubsection`, and raising it numbers the two deeper levels; `\setcounter{section}`/`{figure}`/`{table}`/`{equation}`/`{theorem}` offsets the next counter value) and paint at `\Large`/`\large`/`\normalsize` (the two deepest levels stay bold at the base size), starred headings stay unnumbered, and an optional `[short]` title replaces the long title in the table of contents; the `abstract` environment expands into a centered bold heading and a 9pt body, `\maketitle` joins `\and` authors and turns `\thanks` notes into title footnotes, and `\label` inside a heading (or on its own line after it) resolves `\ref`/`\eqref` to the section number while unknown references print `??`, and `\pageref{label}` reports the formatted page number of that heading after a probe layout (unknown labels print `??`), and `\appendix` restarts sectioning with letters (`A`, `A.1`), and `\tableofcontents` lists the numbered headings through `\subsubsection` with 12pt per-level indentation and a right-aligned page number reached by dot leaders that fill the measure (the default article `tocdepth` of 3; `\setcounter{tocdepth}` changes the depth) while `\listoffigures`/`\listoftables` reproduce the numbered figure/table captions and append each float's page number after dot leaders that fill the measure (an optional `[short]` caption is used there while the long caption stays on the float); `verbatim` environments keep each source line as a monospaced 9pt paragraph indented by 12pt (leading whitespace is normalised), `\verb|...|` renders inline literal text in the mono face, common text commands such as `\LaTeX`, `\TeX`, `\ldots`, `\dots`, `\S`, `\copyright`, `\pounds`, `\ss`/`\ae`/`\oe`/`\o`/`\l`/`\dh`/`\th` and symbol commands such as `\textdegree`/`\textmu`/`\textonehalf`/`\texteuro` expand to their characters, and a control word swallows the spaces that follow it, `\href{url}{text}` keeps its text, and `\url{...}` becomes typewriter text; `\footnote{...}` becomes a numbered 9pt page insertion on the page that mentions it; a `thebibliography` environment is removed from the body, its `\bibitem` entries become numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`, an optional note like `\cite[p.~3]{...}` is dropped, `\citep`/`\citet` behave like `\cite`, `\nocite` is ignored, and `\bibliography`/`\bibliographystyle` lines are consumed without running BibTeX); a `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and resolves `\ref`, and `\includegraphics` embeds the referenced project image (PNG/JPEG/BMP are decoded into a PDF XObject, with a rule placeholder when the file is missing or cannot be decoded), and a standalone `\includegraphics` paragraph becomes an in-text graphic float, while a standalone `\rule{width}{height}` becomes an in-text rule box, with `width=`/`height=` taking dimensions or fractions of `\textwidth`/`\textheight`, `scale=` a percentage of the natural size, `keepaspectratio` shrinking both dimensions to fit, and `\graphicspath` directories searched with common image extensions when the path has no suffix; `longtable` environments are captured through the same tabular path (including their `\endfirsthead`/`\endhead` markers), and a `table` environment becomes a float that carries its captured `tabular` body and a numbered `Table n:` caption whose text sits above the tabular as in LaTeX, while `\caption*` stays unnumbered for either float kind; `\tabcolsep` (or `\setlength{\tabcolsep}`) sets the glue on each side of every tabular column, with LaTeX's 6pt default when unset, and `\renewcommand{\arraystretch}{factor}` (or `\def\arraystretch{factor}`) scales every tabular row height; a `tabular`/`longtable` optional position argument is accepted and ignored, and a row separator `\\[dim]` adds that vertical gap after its row, and `|` column separators paint 0.4pt vertical rules at their column boundaries, and `*{n}{cols}` repeats a column group n times; caption prefixes and the abstract heading can be renamed with `\renewcommand{\figurename}`, `\renewcommand{\tablename}` and `\renewcommand{\abstractname}`, while the bibliography, table of contents and float lists open with `References`/`Contents`/`List of Figures`/`List of Tables` headings renamed by `\renewcommand{\refname}`, `\renewcommand{\contentsname}`, `\renewcommand{\listfigurename}` and `\renewcommand{\listtablename}`; `theorem`/`lemma`/`corollary`/`proposition`/`definition`/`example`/`remark`/`proof` environments get a bold numbered heading (optionally with `[title]`), italic statements for the theorem group, an unnumbered proof whose optional argument replaces its heading text, and `\label`/`\ref` targets; `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` define custom environments with shared counters and section-scoped numbers; `itemize`/`enumerate`/`description` lists nest with depth-aware bullets (`•`, `–`, `*`), lettered/roman sub-labels and 12pt-per-level indentation, items take article's per-level `\topsep`/`\itemsep` plus `\partopsep` above the first item (top level 8+2/4pt at 10pt, 9+3/4.5pt at 11pt and 10+3/5pt at 12pt, with 4+2/2pt, 4.5+3/2pt and 5+3/2pt at the second level; `\setlength{\topsep}`, `\setlength{\itemsep}` and `\setlength{\partopsep}` override them, and a wrapped item hangs its continuation lines at the text indent while its first line stays at the bullet indent), an optional `\item[label]` overrides the generated marker, and `description` items print their term in bold before the definition, and a `\setcounter{enumi}` (or `enumii`/`enumiii`/`enumiv`) line before the first `\item` resumes the enumerate count; `center`/`flushleft`/`flushright` parse their body as blocks (so a nested list, graphic or rule keeps its own handling), a `quotation` environment splits its blank-line-separated paragraphs into blocks indented 20pt on both sides (nested lists add the margins to their own indentation), and `quote` uses the same 20pt margins, while `verse` keeps its explicit line breaks as separate 20pt-indented lines, and a `minipage{w}` environment lays its body out at width `w` (its optional position argument is ignored); `\def\name#1{...}` parameter texts and `\let\alias=\other` aliases are executed as textual definitions; `\newenvironment{name}[n]{begin}{end}` definitions expand their begin/end codes around the environment body, with numbered arguments available in both; `\newif\ifname` flags default to false and `\nametrue`/`\namefalse` assignments, whether in the preamble or the body, select between `\ifname ... \else ... \fi` branches; project previews and PDF exports expand `\input{...}`/`\include{...}` from the project's files (the `.tex` suffix may be omitted) while unknown files stay literal text, and inline a project's own `.sty` files for `\usepackage{name}` and `.cls` files for `\documentclass` (rewritten to `article` with the original options kept), recursively inlining local `\RequirePackage` dependencies (up to eight levels, cycles skipped), inlining local `\input{...}` files inside class/package bodies (unresolved ones are dropped), `\AtBeginDocument`/`\AtEndDocument` bodies are executed while `\makeatletter`/`\makeatother` are stripped, dropping package/class boilerplate (`\ProvidesPackage`/`\ProvidesClass`, `\NeedsTeXFormat`, `\RequirePackage`) and inlining local base classes requested with `\LoadClass`/`\LoadClassWithOptions` (unknown bases keep LaTeX's article fallback); local class and package files execute their `\DeclareOption`/`\ExecuteOptions`/`\ProcessOptions` subset, so options named on `\documentclass[...]` or `\usepackage[...]` run their declaration code and `\ExecuteOptions` supplies defaults, and `\PassOptionsToPackage`/`\PassOptionsToClass` lines are collected from the preamble and merged into the next `\usepackage`/`\documentclass` request; a full class layout implementation and arbitrary package code remain open | +| M6 | class/package execution (`article`, `sn-jnl`) | **partial**: a leading `\noindent` starts a paragraph flush with the measure, `\documentclass[...]` options are read and the article `10pt`/`11pt`/`12pt` base size sets the default paragraph font size and `\baselineskip` (13.6pt/14.5pt), and `\linespread{factor}` (or `\renewcommand{\baselinestretch}{factor}`/`\def\baselinestretch{factor}`) scales that class baseline, while `\newlength{\name}` registers a named length that `\setlength` can assign and a later `\setlength{\parindent}{\name}` can read, and `\addtolength{\name}{...}` adjusts it; the `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom` options (and `\geometry{...}`) adjust the measure and page height; page numbers print centred below the text block, `\setcounter{page}` offsets the printed number, `\addtocounter{page}` shifts it (`\pagenumbering` resets it to 1), `\pagenumbering{roman|Roman|alph|Alph|arabic}` selects the format and `\pagestyle{empty}` suppresses them on every page and `\thispagestyle{empty}` on the first page; `\title`/`\author`/`\date` are captured, `\hypersetup{pdftitle=...}` (also `pdfauthor`/`pdfsubject`/`pdfkeywords`) writes the PDF Info dictionary with UTF-16BE values for non-ASCII text (falling back to `\title`/`\author`), each numbered heading becomes a PDF bookmark in `/Outlines`, nested by heading level and pointing at its page, `\today` expands to the UTC calendar date in the title block and the body, and `\maketitle` expands into the centered article title block at the class sizes (with today's date when `\date` is absent and no date for `\date{}`); numbered `\section`/`\subsection`/`\subsubsection`/`\paragraph`/`\subparagraph` headings advance five-level article counters (article's `\setcounter{secnumdepth}` default of 3 numbers through `\subsubsection`, and raising it numbers the two deeper levels; `\setcounter{section}`/`{figure}`/`{table}`/`{equation}`/`{theorem}` offsets the next counter value) and paint at `\Large`/`\large`/`\normalsize` (the two deepest levels stay bold at the base size), starred headings stay unnumbered, and an optional `[short]` title replaces the long title in the table of contents; the `abstract` environment expands into a centered bold heading and a 9pt body, `\maketitle` joins `\and` authors and turns `\thanks` notes into title footnotes, and `\label` inside a heading (or on its own line after it) resolves `\ref`/`\eqref` to the section number while unknown references print `??`, and `\pageref{label}` reports the formatted page number of that heading after a probe layout (unknown labels print `??`), and `\appendix` restarts sectioning with letters (`A`, `A.1`), and `\tableofcontents` lists the numbered headings through `\subsubsection` with 12pt per-level indentation and a right-aligned page number reached by dot leaders that fill the measure (the default article `tocdepth` of 3; `\setcounter{tocdepth}` changes the depth) while `\listoffigures`/`\listoftables` reproduce the numbered figure/table captions and append each float's page number after dot leaders that fill the measure (an optional `[short]` caption is used there while the long caption stays on the float); `verbatim` environments keep each source line as a monospaced 9pt paragraph indented by 12pt (leading whitespace is normalised), `\verb|...|` renders inline literal text in the mono face, common text commands such as `\LaTeX`, `\TeX`, `\ldots`, `\dots`, `\S`, `\copyright`, `\pounds`, `\ss`/`\ae`/`\oe`/`\o`/`\l`/`\dh`/`\th` and symbol commands such as `\textdegree`/`\textmu`/`\textonehalf`/`\texteuro` expand to their characters, and a control word swallows the spaces that follow it, `\href{url}{text}` keeps its text, and `\url{...}` becomes typewriter text; `\footnote{...}` becomes a numbered 9pt page insertion on the page that mentions it; a `thebibliography` environment is removed from the body, its `\bibitem` entries become numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`, an optional note like `\cite[p.~3]{...}` is dropped, `\citep`/`\citet` behave like `\cite`, `\nocite` is ignored, and `\bibliography`/`\bibliographystyle` lines are consumed without running BibTeX); a `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and resolves `\ref`, and `\includegraphics` embeds the referenced project image (PNG/JPEG/BMP are decoded into a PDF XObject, with a rule placeholder when the file is missing or cannot be decoded), and a standalone `\includegraphics` paragraph becomes an in-text graphic float, while a standalone `\rule{width}{height}` becomes an in-text rule box, with `width=`/`height=` taking dimensions or fractions of `\textwidth`/`\textheight`, `scale=` a percentage of the natural size, `keepaspectratio` shrinking both dimensions to fit, and `\graphicspath` directories searched with common image extensions when the path has no suffix; `longtable` environments are captured through the same tabular path (including their `\endfirsthead`/`\endhead` markers), and a `table` environment becomes a float that carries its captured `tabular` body and a numbered `Table n:` caption whose text sits above the tabular as in LaTeX, while `\caption*` stays unnumbered for either float kind; `\tabcolsep` (or `\setlength{\tabcolsep}`) sets the glue on each side of every tabular column, with LaTeX's 6pt default when unset, and `\renewcommand{\arraystretch}{factor}` (or `\def\arraystretch{factor}`) scales every tabular row height; a `tabular`/`longtable` optional position argument is accepted and ignored, and a row separator `\\[dim]` adds that vertical gap after its row, and `|` column separators paint 0.4pt vertical rules at their column boundaries, and `*{n}{cols}` repeats a column group n times; caption prefixes and the abstract heading can be renamed with `\renewcommand{\figurename}`, `\renewcommand{\tablename}` and `\renewcommand{\abstractname}`, while the bibliography, table of contents and float lists open with `References`/`Contents`/`List of Figures`/`List of Tables` headings renamed by `\renewcommand{\refname}`, `\renewcommand{\contentsname}`, `\renewcommand{\listfigurename}` and `\renewcommand{\listtablename}`; `theorem`/`lemma`/`corollary`/`proposition`/`definition`/`example`/`remark`/`proof` environments get a bold numbered heading (optionally with `[title]`), italic statements for the theorem group, an unnumbered proof whose optional argument replaces its heading text, and `\label`/`\ref` targets; `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` define custom environments with shared counters and section-scoped numbers; `itemize`/`enumerate`/`description` lists nest with depth-aware bullets (`•`, `–`, `*`), lettered/roman sub-labels and 12pt-per-level indentation, items take article's per-level `\topsep`/`\itemsep` plus `\partopsep` above the first item (top level 8+2/4pt at 10pt, 9+3/4.5pt at 11pt and 10+3/5pt at 12pt, with 4+2/2pt, 4.5+3/2pt and 5+3/2pt at the second level; `\setlength{\topsep}`, `\setlength{\itemsep}` and `\setlength{\partopsep}` override them, and a wrapped item hangs its continuation lines at the text indent while its first line stays at the bullet indent), an optional `\item[label]` overrides the generated marker, and `description` items print their term in bold before the definition, and a `\setcounter{enumi}` (or `enumii`/`enumiii`/`enumiv`) line before the first `\item` resumes the enumerate count; `center`/`flushleft`/`flushright` parse their body as blocks (so a nested list, graphic or rule keeps its own handling), a `quotation` environment splits its blank-line-separated paragraphs into blocks indented 20pt on both sides (nested lists add the margins to their own indentation), and `quote` uses the same 20pt margins, while `verse` keeps its explicit line breaks as separate 20pt-indented lines, and a `minipage{w}` environment lays its body out at width `w` (its optional position argument is ignored); `\def\name#1{...}` parameter texts and `\let\alias=\other` aliases are executed as textual definitions; `\newenvironment{name}[n]{begin}{end}` definitions expand their begin/end codes around the environment body, with numbered arguments available in both; `\newif\ifname` flags default to false and `\nametrue`/`\namefalse` assignments, whether in the preamble or the body, select between `\ifname ... \else ... \fi` branches; project previews and PDF exports expand `\input{...}`/`\include{...}` from the project's files (the `.tex` suffix may be omitted) while unknown files stay literal text, and inline a project's own `.sty` files for `\usepackage{name}` and `.cls` files for `\documentclass` (rewritten to `article` with the original options kept), recursively inlining local `\RequirePackage` dependencies (up to eight levels, cycles skipped), inlining local `\input{...}` files inside class/package bodies (unresolved ones are dropped), `\AtBeginDocument`/`\AtEndDocument` bodies are executed while `\makeatletter`/`\makeatother` are stripped, dropping package/class boilerplate (`\ProvidesPackage`/`\ProvidesClass`, `\NeedsTeXFormat`, `\RequirePackage`) and inlining local base classes requested with `\LoadClass`/`\LoadClassWithOptions` (unknown bases keep LaTeX's article fallback); local class and package files execute their `\DeclareOption`/`\ExecuteOptions`/`\ProcessOptions` subset, so options named on `\documentclass[...]` or `\usepackage[...]` run their declaration code and `\ExecuteOptions` supplies defaults, and `\PassOptionsToPackage`/`\PassOptionsToClass` lines are collected from the preamble and merged into the next `\usepackage`/`\documentclass` request; a full class layout implementation and arbitrary package code remain open, and `\textcolor{name}{...}` paints an inline run in one of the standard named colours in both the SVG preview and the PDF | | M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity | ## Current limits @@ -367,7 +367,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph. -The crate currently has 426 unit tests plus ten route-D integration tests and thirty-eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 831 tests (426 route-D unit, 222 engine binary unit, 10 route-D integration, 38 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. +The crate currently has 427 unit tests plus ten route-D integration tests and thirty-eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 834 tests (427 route-D unit, 223 engine binary unit, 10 route-D integration, 38 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. ### M0 incremental demo @@ -415,7 +415,7 @@ Residual approximations, documented rather than special-cased: The `M3`-`M7` stage of the roadmap is implemented to the extent recorded below. The goal ran for 90 rounds and landed 123 commits (`8c42f2d..c9a074b`); the -workspace suite is at 831 tests. +workspace suite is at 834 tests. | Milestone | Evidence | | --- | --- | diff --git a/src/route_d.rs b/src/route_d.rs index ac55207..c110027 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -4559,6 +4559,97 @@ fn strip_hrefs(text: &str) -> String { output } +fn named_color(name: &str) -> Option<[u8; 3]> { + match name.trim().to_ascii_lowercase().as_str() { + "black" => Some([0, 0, 0]), + "white" => Some([255, 255, 255]), + "red" => Some([255, 0, 0]), + "green" => Some([0, 128, 0]), + "blue" => Some([0, 0, 255]), + "cyan" => Some([0, 255, 255]), + "magenta" => Some([255, 0, 255]), + "yellow" => Some([255, 255, 0]), + "gray" | "grey" => Some([128, 128, 128]), + "darkgray" | "darkgrey" => Some([64, 64, 64]), + "lightgray" | "lightgrey" => Some([192, 192, 192]), + "brown" => Some([165, 42, 42]), + "lime" => Some([0, 255, 0]), + "olive" => Some([128, 128, 0]), + "orange" => Some([255, 165, 0]), + "pink" => Some([255, 192, 203]), + "purple" => Some([128, 0, 128]), + "teal" => Some([0, 128, 128]), + "violet" => Some([238, 130, 238]), + _ => None, + } +} + +/// Splits `\textcolor{name}{text}` runs out of a paragraph piece. +fn split_textcolor(text: &str) -> Vec<(Option<[u8; 3]>, String)> { + let mut out = Vec::new(); + let mut rest = text; + let mut plain = String::new(); + while let Some(index) = rest.find("\\textcolor") { + plain.push_str(&rest[..index]); + let after = rest[index + "\\textcolor".len()..].trim_start(); + let Some(after) = after.strip_prefix('{') else { + plain.push_str(&rest[index..]); + rest = ""; + break; + }; + let Some(close) = after.find('}') else { + plain.push_str(&rest[index..]); + rest = ""; + break; + }; + let name = &after[..close]; + let after_name = after[close + 1..].trim_start(); + let Some(body) = after_name.strip_prefix('{') else { + plain.push_str(&rest[index..]); + rest = ""; + break; + }; + let mut depth = 1_usize; + let mut end = None; + for (offset, character) in body.char_indices() { + match character { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + end = Some(offset); + break; + } + } + _ => {} + } + } + let Some(end) = end else { + plain.push_str(&rest[index..]); + rest = ""; + break; + }; + match named_color(name) { + Some(color) => { + if !plain.is_empty() { + out.push((None, std::mem::take(&mut plain))); + } + out.push((Some(color), body[..end].to_string())); + } + None => plain.push_str(&rest[index..index + 1]), + } + rest = &body[end + 1..]; + } + plain.push_str(rest); + if !plain.is_empty() { + out.push((None, plain)); + } + if out.is_empty() { + out.push((None, text.to_string())); + } + out +} + fn inline_math_segments( text: &str, base: ParagraphFont, @@ -4571,35 +4662,47 @@ fn inline_math_segments( let mut found_math = false; let mut found_link = false; let mut found_size = false; + let mut found_color = false; for part in split_hrefs(text) { match part { HrefPart::Plain(piece) => { - let runs = inline_styled_runs(&piece, base) - .unwrap_or_else(|| vec![(base, style.font_size, 0, piece.clone())]); - for (font, size, raise, run_text) in runs { - for (is_math, piece) in split_inline_math(&run_text) { - if is_math { - found_math = true; - segments.push(texrra_tex_core::paragraph::InlineSegment::Math( - parse_math(&piece), - )); - } else if !piece.is_empty() { - if raise != 0 { - found_size = true; - segments.push(texrra_tex_core::paragraph::InlineSegment::Script( - font, size, raise, piece, + for (color, chunk) in split_textcolor(&piece) { + let runs = inline_styled_runs(&chunk, base) + .unwrap_or_else(|| vec![(base, style.font_size, 0, chunk.clone())]); + for (font, size, raise, run_text) in runs { + for (is_math, piece) in split_inline_math(&run_text) { + if is_math { + found_math = true; + segments.push(texrra_tex_core::paragraph::InlineSegment::Math( + parse_math(&piece), )); - } else if size == 655_360 { - segments.push(texrra_tex_core::paragraph::InlineSegment::Text( - font, piece, - )); - } else { - found_size = true; - segments.push( - texrra_tex_core::paragraph::InlineSegment::SizedText( - font, size, piece, - ), - ); + } else if !piece.is_empty() { + if let Some(rgb) = color { + found_color = true; + segments.push( + texrra_tex_core::paragraph::InlineSegment::Color( + font, size, raise, rgb, piece, + ), + ); + } else if raise != 0 { + found_size = true; + segments.push( + texrra_tex_core::paragraph::InlineSegment::Script( + font, size, raise, piece, + ), + ); + } else if size == 655_360 { + segments.push(texrra_tex_core::paragraph::InlineSegment::Text( + font, piece, + )); + } else { + found_size = true; + segments.push( + texrra_tex_core::paragraph::InlineSegment::SizedText( + font, size, piece, + ), + ); + } } } } @@ -4618,7 +4721,7 @@ fn inline_math_segments( } } } - (found_math || found_link || found_size).then_some(segments) + (found_math || found_link || found_size || found_color).then_some(segments) } fn inline_runs(text: &str, base: ParagraphFont) -> Option> { @@ -7830,15 +7933,16 @@ a & b #[test] fn preview_warnings_flag_leaked_commands() { - let json = preview_json(r"See \textcolor{red}{red} and \unknownthing.").expect("preview"); - assert!( - json.contains(r"unsupported command `\\textcolor`"), - "{json}" - ); + let json = preview_json(r"See \unknownthing and \textcolor{red}{red}.").expect("preview"); assert!( json.contains(r"unsupported command `\\unknownthing`"), "{json}" ); + assert!( + !json.contains(r"unsupported command `\\textcolor`"), + "{json}" + ); + assert!(json.contains("#ff0000"), "{json}"); } #[test] @@ -9741,6 +9845,18 @@ A definition. assert!(boxes.iter().any(|box_| box_.character == Some('$'))); } + #[test] + fn textcolor_paints_red_glyphs() { + let source = "Body \\textcolor{red}{red} word."; + let json = preview_json(source).expect("preview"); + assert!(json.contains(r##"fill=\"#ff0000\""##), "{json}"); + assert!(!json.contains("textcolor")); + let pdf = pdf_bytes(source).expect("pdf"); + let text = String::from_utf8_lossy(&pdf); + assert!(text.contains("1.000 0.000 0.000 rg"), "{text}"); + assert!(!text.contains("textcolor")); + } + #[test] fn text_width_sets_the_paragraph_measure() { let long =