diff --git a/README.md b/README.md index 4bbb546..a30308b 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. `\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. `\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, 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. 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), `\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. `\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, 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/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 397bd83..ed19b6c 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -620,6 +620,55 @@ fn page_content( content } +/// Document information written into the PDF Info dictionary. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PdfMetadata { + pub title: Option, + pub author: Option, + pub subject: Option, + pub keywords: Option, +} + +fn pdf_text(value: &str) -> String { + if value.chars().all(|character| { + (' '..='~').contains(&character) + && character != '(' + && character != ')' + && character != '\\' + }) { + format!("({value})") + } else { + let mut text = String::from("'); + text + } +} + +fn metadata_object(metadata: &PdfMetadata) -> Option { + let mut fields = Vec::new(); + if let Some(title) = &metadata.title { + fields.push(format!("/Title {}", pdf_text(title))); + } + if let Some(author) = &metadata.author { + fields.push(format!("/Author {}", pdf_text(author))); + } + if let Some(subject) = &metadata.subject { + fields.push(format!("/Subject {}", pdf_text(subject))); + } + if let Some(keywords) = &metadata.keywords { + fields.push(format!("/Keywords {}", pdf_text(keywords))); + } + if fields.is_empty() { + return None; + } + fields.push("/Producer (texrra route-D)".to_string()); + fields.push("/Creator (texrra route-D)".to_string()); + Some(format!("<< {} >>", fields.join(" "))) +} + /// Write several display lists as a multi-page PDF at the default page origin. pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec { display_lists_to_pdf_with_origin(pages, page_height, PageOrigin::default()) @@ -659,6 +708,7 @@ pub fn display_lists_to_pdf_with_paper( page_height, origin, FontBackend::TrueType, + &PdfMetadata::default(), ) } @@ -676,6 +726,25 @@ pub fn display_lists_to_pdf_with_cm_type1( page_height, origin, FontBackend::ComputerModern, + &PdfMetadata::default(), + ) +} + +/// Write PDFs with Computer Modern Type1 outlines and a document Info dictionary. +pub fn display_lists_to_pdf_with_cm_type1_and_metadata( + pages: &[DisplayList], + page_width: i64, + page_height: i64, + origin: PageOrigin, + metadata: &PdfMetadata, +) -> Vec { + write_pdf( + pages, + page_width, + page_height, + origin, + FontBackend::ComputerModern, + metadata, ) } @@ -685,6 +754,7 @@ fn write_pdf( page_height: i64, origin: PageOrigin, backend: FontBackend, + metadata: &PdfMetadata, ) -> Vec { let width = page_width; let height = page_height; @@ -981,6 +1051,14 @@ fn write_pdf( ) .into_bytes(); + let info_ref = match metadata_object(metadata) { + Some(object) => { + objects.push(object.into_bytes()); + format!(" /Info {} 0 R", objects.len()) + } + None => String::new(), + }; + let mut pdf: Vec = b"%PDF-1.4\n".to_vec(); let mut offsets = Vec::new(); for (index, object) in objects.iter().enumerate() { @@ -998,8 +1076,9 @@ fn write_pdf( } pdf.extend_from_slice( format!( - "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n", + "trailer\n<< /Size {} /Root 1 0 R{} >>\nstartxref\n{}\n%%EOF\n", objects.len() + 1, + info_ref, xref ) .as_bytes(), @@ -1072,6 +1151,48 @@ mod type1_pdf_tests { } #[test] + #[test] + fn metadata_writes_the_pdf_info_dictionary() { + let pages = vec![DisplayList { + width: 612 * 65536, + height: 792 * 65536, + items: Vec::new(), + images: Vec::new(), + }]; + let metadata = PdfMetadata { + title: Some("Plain Title".into()), + author: Some("Ada".into()), + subject: None, + keywords: None, + }; + let pdf = String::from_utf8_lossy(&display_lists_to_pdf_with_cm_type1_and_metadata( + &pages, + 612 * 65536, + 792 * 65536, + PageOrigin::default(), + &metadata, + )) + .to_string(); + assert!(pdf.contains("/Title (Plain Title)")); + assert!(pdf.contains("/Author (Ada)")); + assert!(pdf.contains("/Producer (texrra route-D)")); + assert!(pdf.contains("/Info")); + + let unicode = PdfMetadata { + title: Some("Ωmega".into()), + ..PdfMetadata::default() + }; + let pdf = String::from_utf8_lossy(&display_lists_to_pdf_with_cm_type1_and_metadata( + &pages, + 612 * 65536, + 792 * 65536, + PageOrigin::default(), + &unicode, + )) + .to_string(); + assert!(pdf.contains("/Title , /// `\date{...}` captured from the preamble. date: Option, + pdf_title: Option, + pdf_author: Option, + pdf_subject: Option, + pdf_keywords: Option, /// `thebibliography` entries: label key and entry text, in order. bibliography: Vec<(String, String)>, /// `\newtheorem` definitions from the preamble. @@ -1051,6 +1057,50 @@ fn geometry_counter(geometry: &PageGeometry, name: &str) -> u32 { .unwrap_or(0) } +fn hypersetup_values(line: &str) -> Vec<(String, String)> { + let Some(rest) = line.strip_prefix("\\hypersetup") else { + return Vec::new(); + }; + let Some((body, _)) = braced_group(rest.trim_start()) else { + return Vec::new(); + }; + let mut values = Vec::new(); + let mut depth = 0_usize; + let mut entry = String::new(); + for character in body.chars() { + match character { + '{' => { + depth += 1; + entry.push(character); + } + '}' => { + depth = depth.saturating_sub(1); + entry.push(character); + } + ',' if depth == 0 => { + values.push(entry.trim().to_string()); + entry = String::new(); + } + _ => entry.push(character), + } + } + values.push(entry.trim().to_string()); + values + .into_iter() + .filter_map(|entry| { + let (key, value) = entry.split_once('=')?; + let value = value.trim(); + let value = value + .strip_prefix('{') + .and_then(|inner| inner.strip_suffix('}')) + .unwrap_or(value) + .trim() + .to_string(); + Some((key.trim().to_string(), value)) + }) + .collect() +} + fn strip_page_geometry(source: &str) -> (String, PageGeometry) { let mut geometry = PageGeometry::default(); let mut body = String::new(); @@ -1245,6 +1295,18 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) { .extend(graphics_path_groups(trimmed)); continue; } + if trimmed.starts_with("\\hypersetup") { + for (key, value) in hypersetup_values(trimmed) { + match key.as_str() { + "pdftitle" => geometry.pdf_title = Some(value), + "pdfauthor" => geometry.pdf_author = Some(value), + "pdfsubject" => geometry.pdf_subject = Some(value), + "pdfkeywords" => geometry.pdf_keywords = Some(value), + _ => {} + } + } + continue; + } if let Some(value) = braced_value(trimmed, "\\title") { geometry.title = Some(value); continue; @@ -2107,11 +2169,24 @@ pub fn pdf_bytes_with_images( geometry.suppress_first_page_number, ); } - Ok(display_lists_to_pdf_with_cm_type1( + let metadata = PdfMetadata { + title: geometry + .pdf_title + .clone() + .or_else(|| geometry.title.clone()), + author: geometry + .pdf_author + .clone() + .or_else(|| geometry.author.clone()), + subject: geometry.pdf_subject.clone(), + keywords: geometry.pdf_keywords.clone(), + }; + Ok(display_lists_to_pdf_with_cm_type1_and_metadata( &pages, document.paper_width, document.paper_height, geometry.origin, + &metadata, )) } @@ -7520,6 +7595,15 @@ a & b } #[test] + #[test] + fn hypersetup_writes_the_pdf_info_dictionary() { + let pdf = + pdf_bytes("\\hypersetup{pdftitle={My Title},pdfauthor={Ada}}\n\nBody.").expect("pdf"); + let text = String::from_utf8_lossy(&pdf); + assert!(text.contains("/Title (My Title)")); + assert!(text.contains("/Author (Ada)")); + } + fn pageref_reports_the_page_of_its_heading() { let source = "\\pagestyle{empty}\n\n\\section{One}\n\nFirst page.\n\n\\newpage\n\n\\section{Two}\\label{sec:two}\n\nSee page \\pageref{sec:two}."; let json = preview_json(source).expect("preview");