Parse delimited macro arguments
This commit is contained in:
1 parent
269c633233
commit
d1d6672503
3 files changed
+150
-5
No files matched your search
@@ -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`). 890 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 892 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.
|
||||
|
||||
+2
-2
@@ -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; `Line truncated
|
||||
| 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; `Line truncated
|
||||
| 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 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 890 tests (427 route-D unit, 279 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 892 tests (427 route-D unit, 281 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
|
||||
|
||||
|
||||
+147
-2
@@ -292,6 +292,8 @@ struct MacroDefinition {
|
||||
args: u8,
|
||||
default: Option<String>,
|
||||
body: String,
|
||||
/// Literal parameter text when the macro uses delimited arguments.
|
||||
params: Option<String>,
|
||||
}
|
||||
|
||||
/// A `\newenvironment` definition expanded textually in the body.
|
||||
@@ -392,6 +394,23 @@ fn definition_argument_count(params: &str) -> Option<u8> {
|
||||
Some(count)
|
||||
}
|
||||
|
||||
fn parameter_placeholders(params: &str) -> Option<u8> {
|
||||
let mut count = 0_u8;
|
||||
let mut characters = params.chars();
|
||||
while let Some(character) = characters.next() {
|
||||
if character == '#' {
|
||||
let digit = characters.next()?.to_digit(10)?;
|
||||
if digit == 0 {
|
||||
return None;
|
||||
}
|
||||
count = count.max(digit as u8);
|
||||
} else if character == '\\' {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(count)
|
||||
}
|
||||
|
||||
fn expand_csnames(text: &str) -> String {
|
||||
let mut result = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
@@ -450,7 +469,14 @@ fn edef_definition(line: &str, macros: &[MacroDefinition]) -> Option<MacroDefini
|
||||
let (name, consumed) = control_sequence(rest)?;
|
||||
let rest = &rest[consumed..];
|
||||
let open = rest.find('{')?;
|
||||
let args = definition_argument_count(&rest[..open])?;
|
||||
let params_text = &rest[..open];
|
||||
let (args, params) = match definition_argument_count(params_text) {
|
||||
Some(args) => (args, None),
|
||||
None => (
|
||||
parameter_placeholders(params_text)?,
|
||||
Some(params_text.to_string()),
|
||||
),
|
||||
};
|
||||
let (body, _) = take_group_after_open(&rest[open + 1..])?;
|
||||
let mut body = expand_csnames(&body);
|
||||
if args == 0 {
|
||||
@@ -461,6 +487,7 @@ fn edef_definition(line: &str, macros: &[MacroDefinition]) -> Option<MacroDefini
|
||||
args,
|
||||
default: None,
|
||||
body,
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -482,13 +509,21 @@ fn macro_definition(line: &str) -> Option<MacroDefinition> {
|
||||
let (name, consumed) = control_sequence(rest)?;
|
||||
let rest = &rest[consumed..];
|
||||
let open = rest.find('{')?;
|
||||
let args = definition_argument_count(&rest[..open])?;
|
||||
let params_text = &rest[..open];
|
||||
let (args, params) = match definition_argument_count(params_text) {
|
||||
Some(args) => (args, None),
|
||||
None => (
|
||||
parameter_placeholders(params_text)?,
|
||||
Some(params_text.to_string()),
|
||||
),
|
||||
};
|
||||
let (body, _) = take_group_after_open(&rest[open + 1..])?;
|
||||
return Some(MacroDefinition {
|
||||
name,
|
||||
args,
|
||||
default: None,
|
||||
body,
|
||||
params,
|
||||
});
|
||||
}
|
||||
let rest = line
|
||||
@@ -539,6 +574,7 @@ fn macro_definition(line: &str) -> Option<MacroDefinition> {
|
||||
args,
|
||||
default,
|
||||
body,
|
||||
params: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -665,6 +701,9 @@ fn expand_macro_at(text: &str, macros: &[MacroDefinition]) -> Option<(String, us
|
||||
}
|
||||
let name = format!("\\{}", &after_slash[..length]);
|
||||
let definition = macros.iter().find(|macro_| macro_.name == name)?;
|
||||
if let Some(params) = &definition.params {
|
||||
return expand_delimited(text, definition, params);
|
||||
}
|
||||
let tail = &after_slash[length..];
|
||||
let mut args = Vec::new();
|
||||
let mut consumed = 0_usize;
|
||||
@@ -692,6 +731,80 @@ fn expand_macro_at(text: &str, macros: &[MacroDefinition]) -> Option<(String, us
|
||||
|
||||
/// Expand the small set of LaTeX internal commands used by class and package
|
||||
/// files. Returns the replacement text and the bytes consumed.
|
||||
/// Expand a macro whose parameter text contains delimiters.
|
||||
fn expand_delimited(
|
||||
text: &str,
|
||||
definition: &MacroDefinition,
|
||||
params: &str,
|
||||
) -> Option<(String, usize)> {
|
||||
let after_slash = text.strip_prefix('\\')?;
|
||||
let length = after_slash
|
||||
.find(|character: char| !character.is_ascii_alphabetic())
|
||||
.unwrap_or(after_slash.len());
|
||||
let tail = &after_slash[length..];
|
||||
let mut leading = String::new();
|
||||
let mut delimiters: Vec<String> = Vec::new();
|
||||
let mut literal = String::new();
|
||||
let mut characters = params.chars();
|
||||
let mut first = true;
|
||||
while let Some(character) = characters.next() {
|
||||
if character == '#' {
|
||||
let digit = characters.next()?.to_digit(10)?;
|
||||
if first {
|
||||
leading = std::mem::take(&mut literal);
|
||||
first = false;
|
||||
} else {
|
||||
delimiters.push(std::mem::take(&mut literal));
|
||||
}
|
||||
if digit == 0 || digit as u8 != delimiters.len() as u8 + 1 {
|
||||
return None;
|
||||
}
|
||||
} else {
|
||||
literal.push(character);
|
||||
}
|
||||
}
|
||||
delimiters.push(literal);
|
||||
let mut consumed = 1 + length;
|
||||
let mut rest = tail;
|
||||
let trimmed = rest.trim_start();
|
||||
consumed += rest.len() - trimmed.len();
|
||||
rest = trimmed;
|
||||
if !leading.is_empty() {
|
||||
rest = rest.strip_prefix(&leading)?;
|
||||
consumed += leading.len();
|
||||
}
|
||||
let mut args = Vec::new();
|
||||
for delimiter in &delimiters {
|
||||
if delimiter.is_empty() {
|
||||
let trimmed = rest.trim_start();
|
||||
consumed += rest.len() - trimmed.len();
|
||||
rest = trimmed;
|
||||
if let Some(after_open) = rest.strip_prefix('{') {
|
||||
let (argument, used) = take_group_after_open(after_open)?;
|
||||
args.push(argument);
|
||||
consumed += 1 + used;
|
||||
rest = &after_open[used..];
|
||||
} else {
|
||||
let character = rest.chars().next()?;
|
||||
args.push(character.to_string());
|
||||
consumed += character.len_utf8();
|
||||
rest = &rest[character.len_utf8()..];
|
||||
}
|
||||
} else {
|
||||
let position = rest.find(delimiter)?;
|
||||
let mut argument = rest[..position].to_string();
|
||||
if argument.starts_with('{') && argument.ends_with('}') {
|
||||
argument = argument[1..argument.len() - 1].to_string();
|
||||
}
|
||||
args.push(argument);
|
||||
consumed += position + delimiter.len();
|
||||
rest = &rest[position + delimiter.len()..];
|
||||
}
|
||||
}
|
||||
let expanded = substitute_macro_args(&definition.body, &args);
|
||||
Some((expanded, consumed))
|
||||
}
|
||||
|
||||
fn latex_internal_at(rest: &str, macros: &[MacroDefinition]) -> Option<(String, usize)> {
|
||||
let boundary = |after: &str| {
|
||||
after
|
||||
@@ -1925,6 +2038,7 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
||||
args: 0,
|
||||
default: None,
|
||||
body: operator,
|
||||
params: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1952,6 +2066,7 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
||||
args: 0,
|
||||
default: None,
|
||||
body: body.to_string(),
|
||||
params: None,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@@ -2005,12 +2120,14 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
||||
args: 0,
|
||||
default: None,
|
||||
body: String::new(),
|
||||
params: None,
|
||||
});
|
||||
geometry.macros.push(MacroDefinition {
|
||||
name,
|
||||
args: definition.args,
|
||||
default: definition.default,
|
||||
body: definition.body,
|
||||
params: None,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@@ -11149,6 +11266,31 @@ See \ref{fig:a} and \ref{tab:b}.";
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delimited_macro_arguments_parse() {
|
||||
let source = concat!(r"\def\pair#1,#2{(#1|#2)}", "\n\n", r"Body \pair a,b.");
|
||||
let (body, geometry) = geometry_and_body(source);
|
||||
assert_eq!(body.trim(), "Body (a|b).");
|
||||
assert_eq!(geometry.macros[0].params.as_deref(), Some("#1,#2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delimited_arguments_accept_braced_groups() {
|
||||
let source = concat!(
|
||||
r"\def\swap#1/#2{(#2/#1)}",
|
||||
"\n\n",
|
||||
r"\swap {left right}/{right side}."
|
||||
);
|
||||
let (body, _) = geometry_and_body(source);
|
||||
assert!(body.contains("(right side/left right)."), "{body:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delimited_arguments_allow_a_leading_literal() {
|
||||
let source = concat!(r"\def\angle<#1>{<#1>}", "\n\n", r"\angle<x>.");
|
||||
let (body, _) = geometry_and_body(source);
|
||||
assert!(body.contains("<x>."), "{body:?}");
|
||||
}
|
||||
|
||||
fn newcommand_definitions_expand_in_the_body() {
|
||||
let source = "\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\pair}[2]{(#1,#2)}\n\n$\\R$ and $\\pair{x}{y}$";
|
||||
let (body, geometry) = geometry_and_body(source);
|
||||
@@ -11220,12 +11362,14 @@ See \ref{fig:a} and \ref{tab:b}.";
|
||||
args: 0,
|
||||
default: None,
|
||||
body: "\\b".into(),
|
||||
params: None,
|
||||
},
|
||||
MacroDefinition {
|
||||
name: "\\b".into(),
|
||||
args: 0,
|
||||
default: None,
|
||||
body: "B".into(),
|
||||
params: None,
|
||||
},
|
||||
];
|
||||
assert_eq!(expand_macros("\\a", &definitions), "B");
|
||||
@@ -11234,6 +11378,7 @@ See \ref{fig:a} and \ref{tab:b}.";
|
||||
args: 0,
|
||||
default: None,
|
||||
body: "\\loop".into(),
|
||||
params: None,
|
||||
}];
|
||||
assert_eq!(expand_macros("\\loop", &recursive), "\\loop");
|
||||
assert_eq!(expand_macros("\\missing", &definitions), "\\missing");
|
||||
|
||||
Reference in new issue
Block a user