Skip to main content

latexml_core/common/
font.rs

1use std::{
2  borrow::Cow,
3  cmp::max,
4  fmt,
5  hash::{Hash, Hasher},
6  rc::Rc,
7  sync::LazyLock,
8};
9
10/// Note that this has evolved way beynond just "font",
11/// but covers text properties (or even display properties) in general
12/// including basic font information, color & background color
13/// as well as encoding and language information.
14///
15/// NOTE: This is now in Common that it may evolve to be useful in Post processing...
16use regex::Regex;
17use rustc_hash::FxHashMap as HashMap;
18
19use crate::{
20  BoxOps, Digested, DigestedData, Result,
21  binding::content::{fontmap_family_key_syms, fontmap_key_syms, load_font_map, preload_font_map},
22  common::{
23    arena::{self, SymHashMap, SymStr},
24    color::{self, Color},
25    dimension::Dimension,
26    numeric_ops::{NumericOps, UNITY, UNITY_F64, kround},
27    store::Stored,
28  },
29  state::*,
30};
31
32pub mod coverage;
33pub mod standard_metrics;
34pub mod tfm;
35
36/// The family and encoding `decode_fontname` gives a font name (`None`: not a font name).
37type NamedFontClass = Option<(Option<Cow<'static, str>>, Option<Cow<'static, str>>)>;
38
39thread_local! {
40  /// `NamedFontClass` per font name, for `Font::measuring_tfm`.
41  static NAMED_FONT_CLASS: std::cell::RefCell<HashMap<String, NamedFontClass>> =
42    std::cell::RefCell::new(HashMap::default());
43}
44use standard_metrics::{MetricData, STDMETRICS};
45
46use crate::pin;
47
48pub type Fontmap = Rc<[Option<char>]>;
49
50static DEFFAMILY: &str = "serif";
51static DEFSERIES: &str = "medium";
52static DEFSHAPE: &str = "upright";
53/// Perl: $DEFCOLOR = Black = Color::rgb(0,0,0)
54static DEFCOLOR: Color = color::BLACK;
55// Perl: $DEFBACKGROUND = undef (transparent), $DEFLANGUAGE = undef
56// These are intentionally None in text_default/math_default.
57static DEFOPACITY: &str = "1";
58static DEFENCODING: &str = "OT1";
59/// Perl: sub DEFSIZE() { return $STATE->lookupValue('NOMINAL_FONT_SIZE') || 10; }
60/// Reads NOMINAL_FONT_SIZE from state, defaulting to 10.0. Perl uses the value
61/// directly as a float (`Common/Font.pm:44`) — the `11pt` class option is
62/// `10.95` (LaTeX's `\@xipt`), so this must NOT truncate via `lookup_int` (#542).
63pub fn defsize() -> f64 {
64  let v = lookup_float("NOMINAL_FONT_SIZE").map_or(0.0, |f| f.0);
65  if v > 0.0 { v } else { 10.0 }
66}
67
68pub const TEXT_FONTS: [&str; 6] = ["cmr", "cmm", "cmsy", "cmex", "amsa", "amsb"];
69pub const MATH_FONTS: [&str; 6] = ["cmm", "cmsy", "cmex", "amsa", "amsb", "cmr"];
70
71pub const FLAG_FORCE_FAMILY: u8 = 0x1;
72pub const FLAG_FORCE_SERIES: u8 = 0x2;
73pub const FLAG_FORCE_SHAPE: u8 = 0x4;
74pub const FLAG_EMPH: u8 = 0x10;
75
76pub static FONT_TEXT_DEFAULT: LazyLock<Font> = LazyLock::new(Font::text_default);
77static LATIN_LETTER_RE: LazyLock<Regex> =
78  LazyLock::new(|| Regex::new(r"^[\p{Latin}&&\pL]$").unwrap());
79static GREEK_LETTER_RE: LazyLock<Regex> =
80  LazyLock::new(|| Regex::new(r"^[\p{Greek}&&\pL]$").unwrap());
81static UPPER_LETTER_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[\p{Lu}]$").unwrap());
82static DIGIT_LETTER_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[\p{N}]$").unwrap());
83#[rustfmt::skip]
84static FONT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(xylubt|xyluat|xydash|xycmbt|xycmat|xycirc|xybtip|xybsql|xyatip|ul9|ugq|uaq|txtt|txsyb|txsya|txss|txr|txmi|pzd|pzc|pxsyb|pxsya|pxr|pxmi|put|ptm|psy|ppl|pnc|phv|pcr|pbk|pag|msy|msx|msb|msa|manfnt|linew|line|lcirclew|lcircle|futs|futmi|futm|eus|eur|euf|euex|cmvtt|cmtt|cmtl|cmt|cmsy|cmssqi|cmssq|cmss|cmsltt|cmr|cmmib|cmm|cmfr|cmfib|cmex|cmdunh|cmdh|cmu|cmbsy|cmbrs|cmbrm|cmbr|cm|ccy|ccr|ccm|ccitt|bch|bbold|bbmss|bbm)(sbc|sb|mc|m|bx|bm|bc|b|)(sl|sc|n|it|i|csc|)(\d*)$").unwrap());
85//======================================================================
86// Mappings from various forms of names or component names in TeX
87// Given a font, we'd like to map it to the "logical" names derived from LaTeX,
88// (w/ loss of fine grained control).
89// I'd like to use Karl Berry's font naming scheme
90// (See http://www.tug.org/fontname/html/)
91// but it seems to be a one-way mapping, and moreover, doesn't even fit CM fonts!
92// We'll assume a sloppier version:
93//   family + series + variant + size
94// NOTE: This probably doesn't really belong in here...
95
96static FONT_FAMILY: LazyLock<HashMap<&'static str, Font>> = LazyLock::new(|| {
97  raw_map!(
98    "cmr"  => fontmap!(family => "serif"),      "cmss"  => fontmap!(family => "sansserif"),
99    "cmtt" => fontmap!(family => "typewriter"), "cmvtt" => fontmap!(family => "typewriter"),
100    "cmt"  => fontmap!(family => "serif"),
101    "cmsltt" => fontmap!(family => "typewriter", shape => "slanted"),
102    "cmssq" => fontmap!(family => "sansserif"),
103    "cmssqi" => fontmap!(family => "sansserif", shape => "italic"),
104    "cmdunh" => fontmap!(family => "serif"),
105    "cmu"   => fontmap!(family => "serif"),
106    "cmfib" => fontmap!(family => "serif"),      "cmfr"  => fontmap!(family => "serif"),
107    "cmdh"  => fontmap!(family => "serif"),      "cm"    => fontmap!(family => "serif"),
108    "ptm"   => fontmap!(family => "serif"),      "ppl"   => fontmap!(family => "serif"),
109    "pnc"   => fontmap!(family => "serif"),      "pbk"   => fontmap!(family => "serif"),
110    "phv"   => fontmap!(family => "sansserif"),  "pag"   => fontmap!(family => "serif"),
111    "pcr"   => fontmap!(family => "typewriter"), "pzc"   => fontmap!(family => "script"),
112    "put"   => fontmap!(family => "serif"),      "bch"   => fontmap!(family => "serif"),
113    "psy"   => fontmap!(family => "symbol"),     "pzd"   => fontmap!(family => "dingbats"),
114    "ccr"   => fontmap!(family => "serif"),      "ccy"   => fontmap!(family => "symbol"),
115    // Computer Concrete text (Perl Common/Font.pm L92). Sits with `ccr` here
116    // rather than beside its Perl neighbours `ccm`/`ccitt` below, which this
117    // table groups as math fonts.
118    "cct"   => fontmap!(family => "serif"),
119    "cmbr"  => fontmap!(family => "sansserif"),  "cmtl"  => fontmap!(family => "typewriter"),
120    "cmbrs" => fontmap!(family => "symbol"),     "ul9"   => fontmap!(family => "typewriter"),
121    "txr"   => fontmap!(family => "serif"),      "txss"  => fontmap!(family => "sansserif"),
122    "txtt"  => fontmap!(family => "typewriter"),
123    // Modern family codes ABSENT from Perl's %font_family (Common/Font.pm) —
124    // candidate to upstream. Without them, `\fontfamily{\ttdefault}
125    // \selectfont` (fancyvrb's font setup) LOSES the abstract family when a
126    // font package repoints \ttdefault: colm2026_conference loads
127    // `inconsolata` (\ttdefault = zi4), so boxed Verbatim prompts dropped
128    // ltx_font_typewriter and the browser painted full-size serif prose
129    // inside frames TeX measured as \small monospace — border collisions
130    // and text rivers (witness 2605.00468, Prompts 1-7).
131    // Latin Modern:
132    "lmr"   => fontmap!(family => "serif"),      "lmss"  => fontmap!(family => "sansserif"),
133    "lmtt"  => fontmap!(family => "typewriter"), "lmvtt" => fontmap!(family => "typewriter"),
134    // TeX Gyre:
135    "qpl"   => fontmap!(family => "serif"),      "qtm"   => fontmap!(family => "serif"),
136    "qbk"   => fontmap!(family => "serif"),      "qcs"   => fontmap!(family => "serif"),
137    "qhv"   => fontmap!(family => "sansserif"),  "qag"   => fontmap!(family => "sansserif"),
138    "qcr"   => fontmap!(family => "typewriter"), "qzc"   => fontmap!(family => "script"),
139    // inconsolata (zi4), Bera Mono (fvm), Bera Serif/Sans (fve/fvs),
140    // DejaVu Mono (DejaVuSansMono-TLF is fontspec-era; the NFSS code):
141    "zi4"   => fontmap!(family => "typewriter"), "fi4"   => fontmap!(family => "typewriter"),
142    "fvm"   => fontmap!(family => "typewriter"), "fve"   => fontmap!(family => "serif"),
143    "fvs"   => fontmap!(family => "sansserif"),
144    // Source Code/Sans/Serif Pro, Fira:
145    "zsourcecodepro" => fontmap!(family => "typewriter"),
146    "SourceCodePro-TLF" => fontmap!(family => "typewriter"),
147    "FiraMono-TLF" => fontmap!(family => "typewriter"),
148    "FiraSans-TLF" => fontmap!(family => "sansserif"),
149    "txsya" => fontmap!(encoding => "AMSa"),     "txsyb" => fontmap!(encoding => "AMSb"),
150    "pxr"   => fontmap!(family => "serif"),
151    "pxsya" => fontmap!(encoding => "AMSa"),     "pxsyb" => fontmap!(encoding => "AMSb"),
152    "futs"  => fontmap!(family => "serif"),
153    "uaq"   => fontmap!(family => "serif"),      "ugq"   => fontmap!(family => "sansserif"),
154    // Pretend to recognize plain & latex's extra fonts
155    "manfnt"  => fontmap!(family => "graphic", encoding => "manfnt"),
156    "line"    => fontmap!(family => "graphic", encoding => "line"),
157    "linew"   => fontmap!(family => "graphic", encoding => "line", series => "bold"),
158    "lcircle" => fontmap!(family => "graphic", encoding => "lcircle"),
159    "lcirclew" => fontmap!(family => "graphic", encoding => "lcircle", series => "bold"),
160    // Pretend to recognize xy's fonts
161    "xydash" => fontmap!(family => "graphic"), "xyatip" => fontmap!(family => "graphic"),
162    "xybtip" => fontmap!(family => "graphic"), "xybsql" => fontmap!(family => "graphic"),
163    "xycirc" => fontmap!(family => "graphic"), "xycmat" => fontmap!(family => "graphic"),
164    "xycmbt" => fontmap!(family => "graphic"), "xyluat" => fontmap!(family => "graphic"),
165    "xylubt" => fontmap!(family => "graphic"),
166    "eur"   => fontmap!(family => "serif"),      "eus"   => fontmap!(family => "script"),
167    "euf"   => fontmap!(family => "fraktur"),    "euex"  => fontmap!(encoding => "OMX"),
168    // yfonts' families (yfonts.sty `\gothdefault` ygoth, `\swabdefault` yswab,
169    // `\frakdefault` yfrak), which yfonts_sty.rs selects as gothic, schwabacher
170    // and fraktur: a size switch re-selects `\f@family` (dialect.rs), so these
171    // codes must map back. Absent from Perl's %font_family.
172    "ygoth" => fontmap!(family => "gothic"),     "yswab" => fontmap!(family => "schwabacher"),
173    "yfrak" => fontmap!(family => "fraktur"),
174    // The following are actually math fonts.
175    "ccm"   => fontmap!(family => "serif", shape => "italic"),
176    "cmm"   => fontmap!(family => "math", shape => "italic", encoding => "OML"),
177    "cmex"  => fontmap!(encoding => "OMX"),
178    "cmsy"  => fontmap!(encoding => "OMS"),
179    "ccitt" => fontmap!(family => "typewriter", shape => "italic"),
180    "cmbrm" => fontmap!(family => "sansserif", shape => "italic"),
181    "futm"  => fontmap!(family => "serif", shape => "italic"),
182    "futmi" => fontmap!(family => "serif", shape => "italic"),
183    "txmi"  => fontmap!(family => "serif", shape => "italic"),
184    "pxmi"  => fontmap!(family => "serif", shape => "italic"),
185    // cmmib already in Perl
186    "bbm"   => fontmap!(family => "blackboard"),
187    "bbold" => fontmap!(family => "blackboard"),
188    "bbmss" => fontmap!(family => "blackboard"),
189    // some ams fonts
190    "cmmib" => fontmap!(family => "italic", series   => "bold"),
191    "cmbsy" => fontmap!(series => "bold", encoding => "OMS"),
192    "msa"   => fontmap!(encoding => "AMSa"),
193    "msb"   => fontmap!(encoding => "AMSb"),
194    // Are these really the same?
195    "msx" => fontmap!(encoding => "AMSa"),
196    "msy" => fontmap!(encoding => "AMSb")
197  )
198});
199/// Maps the "series code" to an abstract font series name
200static FONT_SERIES: LazyLock<HashMap<&'static str, Font>> = LazyLock::new(|| {
201  raw_map!(
202    "" => Font::default(), "m" => fontmap!(series => "medium"),
203      "mc" => fontmap!(series => "medium"),
204    "b"  => fontmap!(series => "bold"),   "bc"  => fontmap!(series => "bold"),
205      "bx" => fontmap!(series => "bold"),
206    "sb" => fontmap!(series => "bold"),   "sbc" => fontmap!(series => "bold"),
207      "bm" => fontmap!(series => "bold")
208  )
209});
210
211/// Maps the "shape code" to an abstract font shape name.
212static FONT_SHAPE: LazyLock<HashMap<&'static str, Font>> = LazyLock::new(|| {
213  raw_map!(
214    "" => Font::default(), "n" => fontmap!(shape => "upright"),
215      "i" => fontmap!(shape => "italic"), "it" => fontmap!(shape => "italic"),
216      "sl" => fontmap!(shape => "slanted"),
217      "sc" => fontmap!(shape => "smallcaps"), "csc" => fontmap!(shape => "smallcaps")
218  )
219});
220
221/// Symbolic font sizes, relative to the NOMINAL_FONT_SIZE (often 10)
222/// extended logical font sizes, based on nominal document size of 10pts
223/// Possibly should simply use absolute font point sizes, as declared in class...
224static FONT_SIZE: LazyLock<HashMap<&'static str, f64>> = LazyLock::new(|| {
225  raw_map!(
226"tiny"   => 0.5,   "SMALL" => 0.7, "Small" => 0.8,  "small" => 0.9,
227"normal" => 1.0,   "large" => 1.2, "Large" => 1.44, "LARGE" => 1.728,
228"huge"   => 2.074, "Huge"  => 2.488,
229"big"    => 1.2,   "Big"   => 1.6, "bigg" => 2.1, "Bigg" => 2.6)
230});
231
232static SCRIPT_STYLE_MAP: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
233  raw_map!(
234  "display" => "script", "text" => "script",
235  "script" => "scriptscript", "scriptscript" => "scriptscript")
236});
237
238static FRAC_STYLE_MAP: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
239  raw_map!(
240  "display" => "text", "text" => "script",
241  "script" => "scriptscript", "scriptscript" => "scriptscript")
242});
243
244static STYLE_SIZE: LazyLock<HashMap<&'static str, usize>> = LazyLock::new(|| {
245  raw_map!(
246  "display" => 10, "text" => 10, "script" => 7, "scriptscript" => 5)
247});
248
249// Note: Perl's Font.pm has a %mathstylesize table used in specialize()
250// font-size scaling, but the path is commented out in Perl too. We don't
251// implement this yet — restore from git history if/when specialize wants
252// math-style-based size adjustment.
253
254/// A special form of merge when copying/moving nodes to a new context,
255/// particularly math which become scripts or such.
256static MATH_STYLE_STEP: LazyLock<HashMap<&'static str, HashMap<&'static str, i32>>> =
257  LazyLock::new(|| {
258    raw_map!(
259  "display" => raw_map!(
260    "display" => 0, "text" => 1, "script" => 2, "scriptscript" => 3),
261  "text"=> raw_map!("display" => -1, "text" => 0, "script" => 1, "scriptscript" => 2),
262  "script"=> raw_map!("display" => -2, "text" => -1, "script" => 0, "scriptscript" => 1),
263  "scriptscript" => raw_map!("display" => -3, "text" => -2, "script" => -1, "scriptscript" => 0))
264  });
265static STEP_MATH_STYLE: LazyLock<HashMap<&'static str, HashMap<i32, &'static str>>> =
266  LazyLock::new(|| {
267    raw_map!(
268"display" => raw_map!(-3 => "display", -2 => "display", -1 => "display",
269  0 => "display", 1 => "text", 2 => "script", 3 => "scriptscript"),
270"text" => raw_map!(-3 => "display", -2 => "display", -1 => "display",
271  0 => "text", 1 => "script", 2 => "scriptscript", 3 => "scriptscript"),
272"script" => raw_map!(-3 => "display", -2 => "display", -1 => "text",
273  0 => "script", 1 => "scriptscript", 2 => "scriptscript", 3 => "scriptscript"),
274"scriptscript" => raw_map!(-3 => "display", -2 => "text", -1 => "script",
275  0 => "scriptscript", 1 => "scriptscript", 2 => "scriptscript", 3 => "scriptscript"))
276  });
277
278/// Map Font (family, series, shape) to a TeX fontname (tfm).
279/// Returns `None` if the combo isn't recognized. Matching on a tuple
280/// of `&str` lets callers skip allocating an intermediate
281/// `format!("{family}_{series}_{shape}")` key per lookup. Callers use
282/// `lookup_metric_name(family, series, shape)` instead of the former
283/// `METRIC_MAP.get(&format!(…))` pattern.
284fn lookup_metric_name(family: &str, series: &str, shape: &str) -> Option<&'static str> {
285  match (family, series, shape) {
286    ("serif", "medium", "upright") => Some("cmr"),
287    ("serif", "medium", "slanted") => Some("cmsl"),
288    ("serif", "medium", "italic") => Some("cmti"),
289    ("serif", "medium", "uprightitalic") => Some("cmu"),
290    ("serif", "bold", "upright") => Some("cmbx"),
291    ("serif", "medum", "smallcaps") => Some("cmcsc"), // typo preserved from Perl
292    ("sansserif", "medium", "upright") => Some("cmss"),
293    ("sansserif", "medium", "italic") => Some("cmssi"),
294    ("sansserif", "bold", "upright") => Some("cmssbx"),
295    ("typewriter", "medium", "upright") => Some("cmtt"),
296    ("typewriter", "medium", "slanted") => Some("cmsltt"),
297    ("math", "medium", "italic") => Some("cmmi"),
298    ("math", "medium", "upright") => Some("cmr"),
299    ("math", "bold", "italic") => Some("cmmib"),
300    _ => None,
301  }
302}
303
304// Fallback fontnames for looking up random Unicode,
305// when they're not in the indicated FontMap
306// Perl #2845 (Common/Font.pm L530): `ifgeo` (STDMETRICS `ifgeo10`) for the geometric shapes, the diamonds among them.
307static METRIC_FALLBACKS: [&str; 7] = ["cmr", "cmmi", "cmsy", "cmex", "msam", "msbm", "ifgeo"];
308
309// Math bearing atom types
310// 0=Ord, 1=Op, 2=Bin, 3=Rel, 4=Open, 5=Close, 6=Punct, 7=Inner
311#[rustfmt::skip]
312static MATH_ATOM_TYPE: LazyLock<HashMap<&'static str, usize>> = LazyLock::new(|| {
313  raw_map!(
314    "ID" => 0,
315    "BIGOP" => 1, "SUMOP" => 1, "INTOP" => 1, "OPERATOR" => 1, "LIMITOP" => 1, "DIFFOP" => 1,
316    "ADDOP" => 2, "MULOP" => 2, "BINOP" => 2, "COMPOSEOP" => 2, "MIDDLE" => 2, "VERTBAR" => 2,
317    "RELOP" => 3, "METARELOP" => 3, "ARROW" => 3,
318    "OPEN" => 4, "CLOSE" => 5,
319    "PUNCT" => 6, "PERIOD" => 6,
320    "ARRAY" => 7, "MODIFIER" => 7
321  )
322});
323
324// Math bearing table: [prev_type][cur_type] => bearing level
325// 0=none, positive=thin(1)/med(2)/thick(3) in display/text,
326// negative: same but suppressed in script/scriptscript
327#[rustfmt::skip]
328static MATH_BEARINGS: [[i8; 8]; 8] = [
329  [ 0,  1, -2, -3,  0,  0,  0, -1],
330  [ 1,  1,  0, -3,  0,  0,  0, -1],
331  [-2, -2,  0,  0, -2,  0,  0, -2],
332  [-3, -3,  0,  0, -3,  0,  0, -3],
333  [ 0,  0,  0,  0,  0,  0,  0,  0],
334  [ 0,  1, -2, -3,  0,  0,  0, -1],
335  [-1, -1,  0, -1, -1, -1, -1, -1],
336  [-1,  1, -2, -3, -1,  0, -1, -1],
337];
338
339// (Perl Font.pm %baseline_map removed with the #2798 S6 sizing rewrite:
340// `compute_boxes_size_stack` now uses the per-line baseline threaded from the
341// List's `\baselineskip` property (recorded by S4 in repack_horizontal),
342// which is the faithful #2798 source — not a static font-size→baseline map.)
343
344/// Global auxiliary for font family lookup
345pub fn lookup_font_family(code: &str) -> Option<&'static Font> { FONT_FAMILY.get(code) }
346
347/// Whether `encoding`'s slots are Unicode code points: `TU`, the encoding of
348/// the Unicode engines (tuenc.def; fonttext.ltx:57-68,93). A slot past the
349/// 8-bit table is then the character itself, and the Latin Modern text fonts
350/// of that format carry the TeX ligatures (tuenc.def:60 `+tlig;`).
351pub fn is_unicode_encoding(encoding: &str) -> bool { encoding == "TU" }
352
353/// Global auxiliary for font series lookup
354pub fn lookup_font_series(code: &str) -> Option<&'static Font> { FONT_SERIES.get(code) }
355
356/// Global auxiliary for font shape lookup
357pub fn lookup_font_shape(code: &str) -> Option<&'static Font> { FONT_SHAPE.get(code) }
358
359/// The NFSS family code that selects an abstract font family: the inverse of
360/// [`lookup_font_family`], giving the code LaTeX's own defaults would put in
361/// `\f@family` (`\rmdefault` `cmr`, `\sfdefault` `cmss`, `\ttdefault` `cmtt`,
362/// all locked in sect13.rs; yfonts' `\gothdefault`/`\swabdefault`) or the one
363/// code the table maps to a symbol or display family. `None` for a family no
364/// NFSS code selects — `nullfont`, `graphic`, `math`, and the binding-only
365/// `oldstyle`, `caligraphic`, `italic`, `smallcaps` families: switching to it
366/// leaves `\f@family` alone, as a raw TeX font switch does.
367pub fn nfss_family_code(family: &str) -> Option<&'static str> {
368  match family {
369    "serif" => Some("cmr"),
370    "sansserif" => Some("cmss"),
371    "typewriter" => Some("cmtt"),
372    "script" => Some("pzc"),
373    "symbol" => Some("psy"),
374    "dingbats" => Some("pzd"),
375    "fraktur" => Some("euf"),
376    "gothic" => Some("ygoth"),
377    "schwabacher" => Some("yswab"),
378    "blackboard" => Some("bbm"),
379    _ => None,
380  }
381}
382
383/// The NFSS series code of an abstract series (`\mddefault` `m`,
384/// `\bfdefault` `bx`), inverse of [`lookup_font_series`].
385pub fn nfss_series_code(series: &str) -> Option<&'static str> {
386  match series {
387    "medium" => Some("m"),
388    "bold" => Some("bx"),
389    _ => None,
390  }
391}
392
393/// The NFSS shape code of an abstract shape (`\updefault` `n`, `\itdefault`
394/// `it`, `\sldefault` `sl`, `\scdefault` `sc`), inverse of
395/// [`lookup_font_shape`]. `normal` is the upright shape plain's `\em` switches
396/// back to (plain_base.pool.ltxml:607).
397pub fn nfss_shape_code(shape: &str) -> Option<&'static str> {
398  match shape {
399    "upright" | "normal" => Some("n"),
400    "italic" => Some("it"),
401    "slanted" => Some("sl"),
402    "smallcaps" => Some("sc"),
403    _ => None,
404  }
405}
406
407/// A font size in points as LaTeX writes `\f@size`: `12`, `14.4`, `10.95`
408/// (`\strip@pt`, latex.ltx:12587).
409pub fn format_points(points: f64) -> String {
410  let text = format!("{points:.2}");
411  let text = text.trim_end_matches('0').trim_end_matches('.');
412  text.to_string()
413}
414
415/// The TeX font file of a text font, as `\font` names one: `cmtt10`, `cmbx9`,
416/// and `cmr10` loaded `at 10.95pt` (`Some` second part) for a size with no
417/// file of its own — the Computer Modern font of the family, series and shape
418/// (`None` for a combination with none). LaTeX's OT1 `.fd` files pick the
419/// nearest design size (ot1cmr.fd); this keeps the size or falls back to 10.
420pub fn tex_font_file_name(
421  family: &str,
422  series: &str,
423  shape: &str,
424  points: f64,
425) -> Option<(String, Option<String>)> {
426  let base = lookup_metric_name(family, series, shape)?;
427  Some(if points.fract() == 0.0 {
428    (format!("{base}{points}"), None)
429  } else {
430    (
431      format!("{base}10"),
432      Some(format!("{}pt", format_points(points))),
433    )
434  })
435}
436
437/// Combine family/series/shape lookups into a single Font (Perl lookupTeXFont)
438pub fn lookup_tex_font(fontname: &str, seriescode: &str, shapecode: &str) -> Font {
439  let mut props = Font::default();
440  if let Some(ffam) = lookup_font_family(fontname) {
441    props = props.merge_ref(ffam);
442  }
443  if let Some(fser) = lookup_font_series(seriescode) {
444    props = props.merge_ref(fser);
445  }
446  if let Some(fsh) = lookup_font_shape(shapecode) {
447    props = props.merge_ref(fsh);
448  }
449  props
450}
451
452/// Find a Font Metric for a given fontname, fallback to 10pt or cmr as needed.
453/// Perl: getMetricForName
454pub fn get_metric_for_name(name: &str) -> &'static MetricData {
455  let base = if let Some(idx) = name.find(|c: char| c.is_ascii_digit()) {
456    &name[..idx]
457  } else {
458    name
459  };
460  // Try exact name first (e.g. "cmr10")
461  if let Some(m) = STDMETRICS.get(name) {
462    return m;
463  }
464  // Try base without size (e.g. "cmr" from "cmr10")
465  if let Some(m) = STDMETRICS.get(base) {
466    return m;
467  }
468  // Try base + "10". Stack-buffer concat avoids the per-call `format!`
469  // heap alloc — `get_metric_for_name` is reached through the
470  // per-character `get_metric` loop, so this is a real allocation
471  // site. Font basenames are short (≤ ~20 ASCII bytes); 32 bytes is
472  // ample padding.
473  let base_bytes = base.as_bytes();
474  if base_bytes.len() + 2 <= 32 {
475    let mut buf = [0u8; 32];
476    buf[..base_bytes.len()].copy_from_slice(base_bytes);
477    buf[base_bytes.len()] = b'1';
478    buf[base_bytes.len() + 1] = b'0';
479    if let Ok(s) = std::str::from_utf8(&buf[..base_bytes.len() + 2])
480      && let Some(m) = STDMETRICS.get(s)
481    {
482      return m;
483    }
484  }
485  // Ultimate fallback to "cmr"
486  STDMETRICS
487    .get("cmr")
488    .expect("STDMETRICS must contain 'cmr'")
489}
490
491/// The TFM parameters `\font` gives a font of this name, per point of its
492/// size — Perl's `getMetricForName` (Common/Font.pm:551-562): the name's own
493/// metric, else its family at 10pt, else Computer Modern Roman at the name's
494/// size, else cmr10; the size is the name's trailing digits (10 without). This
495/// port's size-less and hand-merged entries (`cmr`, `cmbx`, `cmex`, …) carry
496/// no parameters and are passed over, as Perl has none of them. Perl's Error
497/// on the cmr10 fallback is not ported: it fires for valid fonts (`ecrm1000`).
498pub fn font_parameters_for_name(name: &str) -> &'static [f64] {
499  let base = name.trim_end_matches(|c: char| c.is_ascii_digit());
500  let size = if base.len() < name.len() {
501    &name[base.len()..]
502  } else {
503    "10"
504  };
505  [name, &format!("{base}10"), &format!("cmr{size}"), "cmr10"]
506    .into_iter()
507    .filter_map(|candidate| STDMETRICS.get(candidate))
508    .map(|metric| metric.parameters)
509    .find(|parameters| !parameters.is_empty())
510    .unwrap_or(&[])
511}
512
513/// The most parameters a font's array may grow to: TeX's font memory,
514/// `font_mem_size` in TeX Live's texmf.cnf, whose overflow stops TeX (tex.web
515/// §580, "TeX capacity exceeded, sorry [font memory=8000000]").
516pub const FONT_MEM_SIZE: usize = 8_000_000;
517
518pub fn decode_fontname(name: &str, at_opt: Option<f64>, scaled_opt: Option<f64>) -> Option<Font> {
519  if let Some(cap) = FONT_RE.captures(name) {
520    // Perl: my %props = (series => 'medium', shape => 'upright', encoding => 'OT1');
521    let mut props = Font {
522      series: Some(Cow::Borrowed(DEFSERIES)),
523      shape: Some(Cow::Borrowed(DEFSHAPE)),
524      encoding: Some(Cow::Borrowed("OT1")),
525      ..Font::default()
526    };
527    let fam = cap.get(1).map_or("", |m| m.as_str());
528    let ser = cap.get(2).map_or("", |m| m.as_str());
529    let shp = cap.get(3).map_or("", |m| m.as_str());
530    let size_str = cap.get(4).map_or("", |m| m.as_str());
531    if let Some(ffam) = lookup_font_family(fam) {
532      props = props.merge_ref(ffam);
533    }
534    if let Some(fser) = lookup_font_series(ser) {
535      props = props.merge_ref(fser);
536    }
537    if let Some(fsh) = lookup_font_shape(shp) {
538      props = props.merge_ref(fsh);
539    }
540    let mut size = if let Some(at) = at_opt {
541      at
542    } else {
543      let size_f64 = size_str.parse::<f64>().unwrap_or(1.0);
544      if size_f64 == 0.0 { 1.0 } else { size_f64 } // Yes, also if 0, "" (from regexp)
545    };
546    if let Some(scaled) = scaled_opt {
547      size *= scaled;
548    }
549    props.size = Some(size);
550    // Experimental Hack !?!?!?
551    if props.encoding.is_none() {
552      props.encoding = Some(Cow::Borrowed("OT1"));
553    }
554    // TODO: What is this field for?
555    // if let Some(at) = at_opt {
556    //   props.at = Some(s!("{at}pt"));
557    // }
558    Some(props)
559  } else {
560    None
561  }
562}
563
564/// The math class of a glyph `\DeclareMathSymbol`'d from the math italic symbol font (`letters`), which decides the
565/// shape a capital Greek letter takes (`Font::specialize_letters`).
566#[derive(Clone, Copy, Debug, PartialEq, Eq)]
567pub enum LettersClass {
568  /// `\mathalpha`, class 7 (variable family): follows a math alphabet in force, else italic, as a Latin letter.
569  Variable,
570  /// `\mathord`, class 0: the math italic whatever the alphabet, as a lowercase Greek letter.
571  Fixed,
572}
573
574/// A data structure containing Font information, but also related textual properties (such as
575/// color)
576///
577/// This struct is a little interesting, as we want to pass overrides that partially modify (via a
578/// merge) the current font, in each definitional binding. To accommodate that with this struct,
579/// every single field needs to be an Option, in order to unambiguously tell the "intend" of
580/// override (Some) vs no intent (None).
581#[derive(Clone, Default)]
582pub struct Font {
583  pub family:        Option<Cow<'static, str>>,
584  pub series:        Option<Cow<'static, str>>,
585  pub shape:         Option<Cow<'static, str>>,
586  pub size:          Option<f64>,
587  pub color:         Option<Color>,
588  pub bg:            Option<Color>,
589  pub opacity:       Option<Cow<'static, str>>,
590  pub encoding:      Option<Cow<'static, str>>,
591  pub language:      Option<Cow<'static, str>>,
592  pub mathstyle:     Option<Cow<'static, str>>,
593  pub mathstylestep: Option<i32>,
594  pub name:          Option<Cow<'static, str>>,
595  /// While a font selected by `\font` (`name`) is in force, the font it replaced: NFSS's
596  /// `\f@encoding`/`\f@family`/`\f@series`/`\f@shape`/`\f@size`, which a `\font` identifier never
597  /// changes (tex.web §1217) and the next font selection returns to (`merge_ref`). Set where a
598  /// `\font` identifier is selected (`content::merge_font_ref`), so it — not `name`, which a box
599  /// font also carries from its `\textfont` — marks a raw font in force. Not part of the font's
600  /// identity (`Hash`, `PartialEq`): it changes nothing until a selection, and the dump does not
601  /// carry it.
602  pub nfss_font:     Option<std::sync::Arc<Font>>,
603  pub emph:          Option<bool>,
604  pub scripted:      Option<bool>,
605  pub fraction:      Option<bool>,
606  // Note: forcefamily, forceseries, forceshape (& forcebold for compatibility)
607  // are only useful for fonts in math; See the specialize method below.
608  pub forceseries:   Option<bool>,
609  pub forcefamily:   Option<bool>,
610  pub forceshape:    Option<bool>,
611  pub forcebold:     Option<bool>,
612  pub scale:         Option<f64>,
613  pub flags:         Option<u8>,
614}
615
616impl Hash for Font {
617  // We need to implement hash since we have to tell Rust how to hash `f64` values
618  // for now I have decided to go for a precision of 4 digits after the decimal point,
619  // so multiplying by 1000
620  fn hash<H: Hasher>(&self, hasher: &mut H) {
621    self.family.hash(hasher);
622    self.series.hash(hasher);
623    self.shape.hash(hasher);
624    self.size.map(|size| (size * 1000.0) as i64).hash(hasher);
625    // None color hashes same as Some(DEFCOLOR)
626    Some(self.color.unwrap_or(DEFCOLOR)).hash(hasher);
627    self.bg.hash(hasher);
628    self.opacity.hash(hasher);
629    self.encoding.hash(hasher);
630    self.language.hash(hasher);
631    self.mathstyle.hash(hasher);
632    self.mathstylestep.hash(hasher);
633    self.name.hash(hasher);
634    self.emph.hash(hasher);
635    self.scripted.hash(hasher);
636    self.forceseries.hash(hasher);
637    self.forcefamily.hash(hasher);
638    self.forceshape.hash(hasher);
639    self.scale.map(|scale| (scale * 1000.0) as i64).hash(hasher);
640    self.flags.hash(hasher);
641  }
642}
643impl PartialEq for Font {
644  fn eq(&self, other: &Self) -> bool {
645    self.family == other.family
646      && self.series == other.series
647      && self.shape == other.shape
648      && self.size == other.size
649      && !is_diff_font_color(self.color.as_ref(), other.color.as_ref())
650      && self.bg == other.bg
651      && self.opacity == other.opacity
652      && self.encoding == other.encoding
653      && self.language == other.language
654      && self.mathstyle == other.mathstyle
655      && self.mathstylestep == other.mathstylestep
656      && self.name == other.name
657      && self.emph == other.emph
658      && self.scripted == other.scripted
659      && self.fraction == other.fraction
660      && self.forceseries == other.forceseries
661      && self.forcefamily == other.forcefamily
662      && self.forceshape == other.forceshape
663      && self.forcebold == other.forcebold
664      && self.scale == other.scale
665      && self.flags == other.flags
666  }
667}
668impl Eq for Font {}
669impl Font {
670  /// Perl `Font::equals` (Font.pm:333-337): the eleven slots of Perl's font array — family,
671  /// series, shape, size, color, background, opacity, encoding, language, mathstyle and flags — and
672  /// none of the Rust-only fields (`name`, `mathstylestep`, `scale`, …) `PartialEq` also compares,
673  /// which a font merged from a mathchar's fontinfo carries (`$2\mathrm{KL}$`'s digit, whose
674  /// `name` and `OT1` encoding are the fontinfo's). Colors compare by value (OXIDIZED_DESIGN #20);
675  /// unset flags are 0, and an unset encoding is Perl's default `OT1` — Rust's math default leaves
676  /// it unset where Perl's `mathDefault` has `'OT1'` (Font.pm:280-283), so the current font of
677  /// `\mathrm` letters compares equal to a digit's fontinfo font as in Perl. Used by the letters
678  /// and number ligatures (`base_xmath.rs`); witness 2605.31599.
679  pub fn perl_equals(&self, other: &Font) -> bool {
680    self.family == other.family
681      && self.series == other.series
682      && self.shape == other.shape
683      && self.size == other.size
684      && !is_diff_font_color(self.color.as_ref(), other.color.as_ref())
685      && self.bg == other.bg
686      && self.opacity == other.opacity
687      && self.encoding.as_deref().unwrap_or(DEFENCODING)
688        == other.encoding.as_deref().unwrap_or(DEFENCODING)
689      && self.language == other.language
690      && self.mathstyle == other.mathstyle
691      && self.flags.unwrap_or(0) == other.flags.unwrap_or(0)
692  }
693}
694// display is used often for attributes in binding replacements,
695// as in font="#font"
696impl fmt::Display for Font {
697  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
698    write!(f, "{}", self.family.as_ref().unwrap_or(&Cow::Borrowed("")))
699  }
700}
701
702impl fmt::Debug for Font {
703  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
704    let star = Cow::Borrowed("*");
705    write!(f, "Font[")?;
706    write!(f, "{}", self.family.as_ref().unwrap_or(&star))?;
707    write!(f, ",")?;
708    write!(f, "{}", self.series.as_ref().unwrap_or(&star))?;
709    write!(f, ",")?;
710    write!(f, "{}", self.shape.as_ref().unwrap_or(&star))?;
711    write!(f, ",")?;
712    let size_str = self
713      .size
714      .as_ref()
715      .map(|x| x.to_string())
716      .unwrap_or_else(|| String::from('*'));
717    write!(f, "{}", size_str)?;
718    write!(f, ",")?;
719    if let Some(ref c) = self.color {
720      write!(f, "{c}")?;
721    } else {
722      write!(f, "*")?;
723    }
724    write!(f, ",")?;
725    if let Some(ref b) = self.bg {
726      write!(f, "{b}")?;
727    } else {
728      write!(f, "*")?;
729    }
730    write!(f, ",")?;
731    write!(f, "{}", self.opacity.as_ref().unwrap_or(&star))?;
732    write!(f, ",")?;
733    let scale_str = self
734      .scale
735      .as_ref()
736      .map(|x| x.to_string())
737      .unwrap_or_else(|| String::from('*'));
738    write!(f, "{}", scale_str)?;
739    write!(f, ",")?;
740    write!(f, "{}", self.mathstyle.as_ref().unwrap_or(&star))?;
741    // TODO? LaTeXML doesn't seem to emit these
742    // if let Some(ref encoding) = self.encoding {
743    //   parts.push(s!("encoding: {:?}", encoding))
744    // }
745    // if let Some(ref language) = self.language {
746    //   parts.push(s!("language: {:?}", language))
747    // }
748    // if let Some(ref mathstylestep) = self.mathstyle {
749    //   parts.push(s!("mathstylestep: {:?}", mathstylestep))
750    // }
751    // if let Some(ref forceseries) = self.forceseries {
752    //   parts.push(s!("forceseries: {:?}", forceseries))
753    // }
754    // if let Some(ref forcefamily) = self.forcefamily {
755    //   parts.push(s!("forcefamily: {:?}", forcefamily))
756    // }
757    // if let Some(ref forceshape) = self.forceshape {
758    //   parts.push(s!("forceshape: {:?}", forceshape))
759    // }
760    // if let Some(ref scripted) = self.scripted {
761    //   parts.push(s!("scripted: {:?}", scripted))
762    // }
763    write!(f, "]")
764  }
765}
766
767impl Font {
768  pub fn text_default() -> Self {
769    Font {
770      family:        Some(Cow::Borrowed(DEFFAMILY)),
771      series:        Some(Cow::Borrowed(DEFSERIES)),
772      shape:         Some(Cow::Borrowed(DEFSHAPE)),
773      size:          Some(defsize()),
774      color:         None, // None = inherited default (DEFCOLOR); Some = explicitly set
775      bg:            None, // Perl: $DEFBACKGROUND = undef (transparent)
776      opacity:       Some(Cow::Borrowed(DEFOPACITY)),
777      encoding:      Some(Cow::Borrowed(DEFENCODING)),
778      language:      None, // Perl: $DEFLANGUAGE = undef
779      mathstyle:     None,
780      mathstylestep: None,
781      emph:          None,
782      name:          None,
783      nfss_font:     None,
784      scripted:      None,
785      fraction:      None,
786      forceseries:   None,
787      forcefamily:   None,
788      forceshape:    None,
789      forcebold:     None,
790      scale:         None,
791      flags:         None,
792    }
793  }
794  pub fn math_default() -> Self {
795    Font {
796      family:        Some(Cow::Borrowed("math")),
797      series:        Some(Cow::Borrowed(DEFSERIES)),
798      shape:         Some(Cow::Borrowed("italic")),
799      size:          Some(defsize()),
800      color:         None, // None = inherited default (DEFCOLOR); Some = explicitly set
801      bg:            None, // Perl: $DEFBACKGROUND = undef
802      opacity:       Some(Cow::Borrowed(DEFOPACITY)),
803      encoding:      None, // Perl has 'OT1' but Rust char decoding uses encoding differently
804      language:      None, // Perl: $DEFLANGUAGE = undef
805      mathstyle:     Some(Cow::Borrowed("text")),
806      mathstylestep: None,
807      emph:          None,
808      name:          None,
809      nfss_font:     None,
810      scripted:      None,
811      fraction:      None,
812      forceseries:   None,
813      forcefamily:   None,
814      forceshape:    None,
815      forcebold:     None,
816      scale:         None,
817      flags:         None,
818    }
819  }
820
821  pub fn to_hashable(&self) -> u64 {
822    // MUST be deterministic: equal Fonts must hash equal, stably across calls
823    // AND across process runs. `set_node_font`/`get_node_font` use this as the
824    // `_font` key and `node_fonts` map key, so a randomized seed
825    // (`RandomState::new()`, used here previously) gave the same Font a
826    // different id on every call — breaking font dedup and making the document
827    // build run-to-run non-deterministic (intermittent locked-frame/mode
828    // FATALs, e.g. 1510.04473). `FxHasher` has a fixed seed.
829    let mut hasher = rustc_hash::FxHasher::default();
830    Hash::hash(self, &mut hasher);
831    hasher.finish()
832  }
833
834  /// Condensed string showing only non-default components.
835  /// Perl: stringify
836  pub fn stringify(&self) -> String {
837    let fam = self
838      .family
839      .as_deref()
840      .map(|f| if f == "math" { "serif" } else { f });
841    let mut parts: Vec<&str> = Vec::new();
842    if let Some(f) = fam
843      && f != DEFFAMILY
844    {
845      parts.push(f);
846    }
847    if let Some(ref ser) = self.series
848      && ser.as_ref() != DEFSERIES
849    {
850      parts.push(ser);
851    }
852    if let Some(ref shp) = self.shape
853      && shp.as_ref() != DEFSHAPE
854    {
855      parts.push(shp);
856    }
857    // Size: use temporary string for formatting
858    let size_str;
859    if let Some(siz) = self.size
860      && (siz - defsize()).abs() > 0.001
861    {
862      size_str = siz.to_string();
863      parts.push(&size_str);
864    }
865    let color_str;
866    if let Some(ref col) = self.color
867      && *col != DEFCOLOR
868    {
869      color_str = col.to_attribute();
870      parts.push(&color_str);
871    }
872    let bg_str;
873    if let Some(ref bkg) = self.bg {
874      // Perl: $DEFBACKGROUND = undef, so any set bg is non-default
875      bg_str = bkg.to_attribute();
876      parts.push(&bg_str);
877    }
878    if let Some(ref opa) = self.opacity
879      && opa.as_ref() != DEFOPACITY
880    {
881      parts.push(opa);
882    }
883    if let Some(ref ms) = self.mathstyle {
884      parts.push(ms);
885    }
886    let flags_str;
887    if let Some(flags) = self.flags
888      && flags != 0
889    {
890      flags_str = flags.to_string();
891      parts.push(&flags_str);
892    }
893    format!("Font[{}]", parts.join(","))
894  }
895
896  /// Wildcard font matching: if any components are defined in both fonts,
897  /// they must be equal. Perl: match
898  pub fn font_match(&self, other: &Font) -> bool {
899    fn check<T: PartialEq>(a: &Option<T>, b: &Option<T>) -> bool {
900      !(a.is_some() && b.is_some() && a != b)
901    }
902    check(&self.family, &other.family)
903      && check(&self.series, &other.series)
904      && check(&self.shape, &other.shape)
905      && check(&self.size, &other.size)
906      // For color: None = DEFCOLOR, so compare effective colors
907      && !is_diff_font_color(self.color.as_ref(), other.color.as_ref())
908      && check(&self.bg, &other.bg)
909      && check(&self.opacity, &other.opacity)
910      && check(&self.encoding, &other.encoding)
911      && check(&self.language, &other.language)
912      && check(&self.mathstyle, &other.mathstyle)
913  }
914
915  /// Fill in undefined fields from a concrete font.
916  /// Perl: makeConcrete
917  pub fn make_concrete(&self, concrete: &Font) -> Self {
918    Font {
919      family:        self.family.clone().or_else(|| concrete.family.clone()),
920      series:        self.series.clone().or_else(|| concrete.series.clone()),
921      shape:         self.shape.clone().or_else(|| concrete.shape.clone()),
922      size:          self.size.or(concrete.size),
923      color:         self.color.or(concrete.color),
924      bg:            self.bg.or(concrete.bg),
925      opacity:       self.opacity.clone().or_else(|| concrete.opacity.clone()),
926      encoding:      self.encoding.clone().or_else(|| concrete.encoding.clone()),
927      language:      self.language.clone().or_else(|| concrete.language.clone()),
928      mathstyle:     self
929        .mathstyle
930        .clone()
931        .or_else(|| concrete.mathstyle.clone()),
932      flags:         Some(self.flags.unwrap_or(0) | concrete.flags.unwrap_or(0)),
933      mathstylestep: self.mathstylestep.or(concrete.mathstylestep),
934      name:          self.name.clone().or_else(|| concrete.name.clone()),
935      nfss_font:     self
936        .nfss_font
937        .clone()
938        .or_else(|| concrete.nfss_font.clone()),
939      emph:          self.emph.or(concrete.emph),
940      scripted:      self.scripted.or(concrete.scripted),
941      fraction:      self.fraction.or(concrete.fraction),
942      forceseries:   self.forceseries.or(concrete.forceseries),
943      forcefamily:   self.forcefamily.or(concrete.forcefamily),
944      forceshape:    self.forceshape.or(concrete.forceshape),
945      forcebold:     self.forcebold.or(concrete.forcebold),
946      scale:         self.scale.or(concrete.scale),
947    }
948  }
949
950  /// Apply pure style changes (from purestyleChanges) to this font.
951  /// Perl: mergePurestyle
952  pub fn merge_purestyle(&self, changes: &Font) -> Self {
953    let mut new = self.clone();
954    if let Some(scale) = changes.scale
955      && let Some(ref mut sz) = new.size
956    {
957      *sz *= scale;
958    }
959    if changes.color.is_some() {
960      new.color.clone_from(&changes.color);
961    }
962    if changes.bg.is_some() {
963      new.bg.clone_from(&changes.bg);
964    }
965    if changes.opacity.is_some() {
966      new.opacity.clone_from(&changes.opacity);
967    }
968    if let Some(step) = changes.mathstylestep {
969      let cur_style: &str = new.mathstyle.as_deref().unwrap_or("display");
970      if let Some(step_map) = STEP_MATH_STYLE.get(cur_style)
971        && let Some(new_style) = step_map.get(&step)
972      {
973        new.mathstyle = Some(Cow::Borrowed(new_style));
974      }
975    }
976    new
977  }
978
979  /// Compute math bearing (inter-atom spacing) between two boxes.
980  /// Perl: math_bearing
981  pub fn math_bearing(&self, thisbox: &Digested, prevbox: &Digested) -> f64 {
982    let r0 = prevbox
983      .get_property("role")
984      .and_then(|s| match s.into_owned() {
985        Stored::String(sym) => Some(arena::with(sym, |s| s.to_string())),
986        _ => None,
987      })
988      .unwrap_or_else(|| "ID".to_string());
989    let r1 = thisbox
990      .get_property("role")
991      .and_then(|s| match s.into_owned() {
992        Stored::String(sym) => Some(arena::with(sym, |s| s.to_string())),
993        _ => None,
994      })
995      .unwrap_or_else(|| "ID".to_string());
996    let t0 = *MATH_ATOM_TYPE.get(r0.as_str()).unwrap_or(&0);
997    let t1 = *MATH_ATOM_TYPE.get(r1.as_str()).unwrap_or(&0);
998    let bearing = MATH_BEARINGS[t0][t1];
999    let style = self
1000      .get_mathstyle()
1001      .map(|s| s.to_string())
1002      .unwrap_or_else(|| "text".to_string());
1003    if bearing == 0 || (bearing < 0 && style != "display" && style != "text") {
1004      return 0.0;
1005    }
1006    // Look up the bearing register: 1=thinmuskip, 2=medmuskip, 3=thickmuskip
1007    let reg_cs = match bearing.unsigned_abs() {
1008      1 => T_CS!("\\thinmuskip"),
1009      2 => T_CS!("\\medmuskip"),
1010      3 => T_CS!("\\thickmuskip"),
1011      _ => return 0.0,
1012    };
1013    if let Ok(Some(def)) = lookup_definition(&reg_cs)
1014      && let Some(val) = def.value_of(Vec::new())
1015    {
1016      // Perl: $STATE->lookupDefinition(...)->valueOf->spValue
1017      // MuGlue->spValue = fixpoint($skip/UNITY, font->getMUWidth)
1018      //                 = kround((skip/UNITY) * MUWidth)
1019      // The raw skip is in mu*UNITY units; convert to sp via MUWidth.
1020      let skip = val.value_of();
1021      let mu_width = self.get_mu_width() as f64;
1022      return (skip as f64 / UNITY_F64 * mu_width).trunc();
1023    }
1024    0.0
1025  }
1026
1027  pub fn is_sticky(&self) -> bool {
1028    if let Some(ref family) = self.family {
1029      family == "serif" || family == "sansserif" || family == "typewriter"
1030    } else {
1031      false
1032    }
1033  }
1034
1035  // Accessors
1036  pub fn get_family(&self) -> Option<&Cow<'_, str>> { self.family.as_ref() }
1037  pub fn get_series(&self) -> Option<&Cow<'_, str>> { self.series.as_ref() }
1038  pub fn get_shape(&self) -> Option<&Cow<'_, str>> { self.shape.as_ref() }
1039  pub fn get_size(&self) -> Option<f64> { self.size }
1040  pub fn get_color(&self) -> Option<&Color> { self.color.as_ref() }
1041  pub fn get_background(&self) -> Option<&Color> { self.bg.as_ref() }
1042  pub fn get_opacity(&self) -> Option<&Cow<'_, str>> { self.opacity.as_ref() }
1043  pub fn get_encoding(&self) -> Option<&Cow<'_, str>> { self.encoding.as_ref() }
1044  pub fn get_language(&self) -> Option<&Cow<'_, str>> { self.language.as_ref() }
1045  pub fn get_mathstyle(&self) -> Option<&Cow<'_, str>> { self.mathstyle.as_ref() }
1046  pub fn get_flags(&self) -> Option<u8> { self.flags }
1047
1048  // NOTE: In math, NORMALLY, setting any one of
1049  //    family, series or shape
1050  // will, usually, automatically reset the others to thier defaults!
1051  // You must arrange this in the calls....
1052  pub fn merge(&self, other: Font) -> Self { self.merge_ref(&other) }
1053
1054  /// Like `merge` but borrows `other` to avoid requiring callers to own or
1055  /// clone a Font just to pass into merge. Clones only the retained fields
1056  /// from `other` (cheap — Option<Cow<'static,str>> clones are free for
1057  /// Borrowed variants, and most Font fields are None in typical uses).
1058  pub fn merge_ref(&self, other: &Font) -> Self {
1059    // A font selected by `\font` replaces `cur_font` only (tex.web §1217); the next font
1060    // selection — a family, series, shape or encoding declaration, which LaTeX ends with
1061    // `\selectfont` (latex.ltx:12576-12579) — starts from NFSS's font again and ends the raw
1062    // one. Colour, a bare size and math style keep it. Guard
1063    // `perfect_kernel_batch58::raw_font_ends_at_a_font_selection`.
1064    if self.nfss_font.is_some()
1065      && other.name.is_none()
1066      && (other.family.is_some()
1067        || other.series.is_some()
1068        || other.shape.is_some()
1069        || other.encoding.is_some()
1070        || other.forcebold.is_some()
1071        || other.emph == Some(true))
1072    {
1073      return self.nfss_restored().merge_ref(other);
1074    }
1075    // Handle forcebold for compatibility (Perl lines 873-874)
1076    let mut series = other.series.clone();
1077    let mut force_series = other.forceseries;
1078    if other.forcebold == Some(true) {
1079      series = Some(Cow::Borrowed("bold"));
1080      force_series = Some(true);
1081    }
1082    // `forcebold` false is the normal math version (`\unboldmath`, `\mathversion{normal}`, latex.ltx:14092-14095,
1083    // :10545): the series medium again, no longer forced. Perl's merge ignores it (Font.pm:934-935, KNOWN_PERL_ERRORS
1084    // #687), so the bold version stayed to the end of the group (witness 1803.08052, Buras's
1085    // `\boldmath\section{…}\unboldmath`). Guard `perfect_kernel_batch78a::unboldmath_restores_the_normal_math_version`.
1086    let unbold = other.forcebold == Some(false);
1087    if unbold {
1088      series = Some(Cow::Borrowed("medium"));
1089    }
1090
1091    // Build flags from force options
1092    let mut flags: u8 = 0;
1093    if other.forcefamily == Some(true) {
1094      flags |= FLAG_FORCE_FAMILY;
1095    }
1096    if force_series == Some(true) {
1097      flags |= FLAG_FORCE_SERIES;
1098    }
1099    if other.forceshape == Some(true) {
1100      flags |= FLAG_FORCE_SHAPE;
1101    }
1102
1103    let oflags = self.flags.unwrap_or(0);
1104    // Perl: fallback to self if not overridden, or if force-flags on self prevent override
1105    let family = if other.family.is_none() || (oflags & FLAG_FORCE_FAMILY != 0) {
1106      self.family.clone()
1107    } else {
1108      other.family.clone()
1109    };
1110    let series = if !unbold && (series.is_none() || (oflags & FLAG_FORCE_SERIES != 0)) {
1111      self.series.clone()
1112    } else {
1113      series
1114    };
1115    let mut shape = if other.shape.is_none() || (oflags & FLAG_FORCE_SHAPE != 0) {
1116      self.shape.clone()
1117    } else {
1118      other.shape.clone()
1119    };
1120    let mut size = other.size.or(self.size);
1121    let color = other.color.or(self.color);
1122    // Perl: $bg = $$self[5] if (!exists $options{background});
1123    // Only override bg if `other` actually specifies one
1124    let bg = if other.bg.is_some() {
1125      other.bg
1126    } else {
1127      self.bg
1128    };
1129    let opacity = other.opacity.clone().or_else(|| self.opacity.clone());
1130    let encoding = other.encoding.clone().or_else(|| self.encoding.clone());
1131    let language = other.language.clone().or_else(|| self.language.clone());
1132    let mut mathstyle = other.mathstyle.clone().or_else(|| self.mathstyle.clone());
1133    flags |= self.flags.unwrap_or(0);
1134    if unbold {
1135      flags &= !FLAG_FORCE_SERIES;
1136    }
1137
1138    // Dynamic adjustment directives
1139    if let Some(scale) = other.scale
1140      && let Some(ref mut sz) = size
1141    {
1142      *sz *= scale;
1143    }
1144
1145    // Scale factor for mathstyle-based sizing
1146    let style_scale = if let Some(sz) = self.size {
1147      let key: &str = self.mathstyle.as_deref().unwrap_or("display");
1148      sz / *STYLE_SIZE.get(key).unwrap_or(&10) as f64
1149    } else {
1150      1.0
1151    };
1152
1153    if other.size.is_some() {
1154      // Explicitly requested size, use it
1155    } else if other.mathstyle.is_some() {
1156      // Set the size from mathstyle
1157      let ms: &str = mathstyle.as_deref().unwrap_or("display");
1158      size = Some(style_scale * *STYLE_SIZE.get(ms).unwrap_or(&10) as f64);
1159    } else if other.scripted == Some(true) {
1160      // Adjust both the mathstyle & size for scripts
1161      let ms: &str = mathstyle.as_deref().unwrap_or("display");
1162      mathstyle = SCRIPT_STYLE_MAP.get(ms).map(|c| Cow::Borrowed(*c));
1163      let new_ms: &str = mathstyle.as_deref().unwrap_or("display");
1164      size = Some(style_scale * *STYLE_SIZE.get(new_ms).unwrap_or(&10) as f64);
1165    } else if other.fraction == Some(true) {
1166      // Adjust both for fractions
1167      let ms: &str = mathstyle.as_deref().unwrap_or("display");
1168      mathstyle = FRAC_STYLE_MAP.get(ms).map(|c| Cow::Borrowed(*c));
1169      let new_ms: &str = mathstyle.as_deref().unwrap_or("display");
1170      size = Some(style_scale * *STYLE_SIZE.get(new_ms).unwrap_or(&10) as f64);
1171    }
1172
1173    // Emphasis handling (Perl lines 909-912)
1174    if other.emph == Some(true) {
1175      shape = if shape.as_deref() == Some("italic") {
1176        Some(Cow::Borrowed("upright"))
1177      } else {
1178        Some(Cow::Borrowed("italic"))
1179      };
1180      flags |= FLAG_EMPH;
1181    }
1182    // Disable emph in math (Perl: $flags &= ~$FLAG_EMPH if $mathstyle)
1183    if mathstyle.is_some() {
1184      flags &= !FLAG_EMPH;
1185    }
1186
1187    let newfont = Font {
1188      family,
1189      series,
1190      shape,
1191      size,
1192      color,
1193      bg,
1194      opacity,
1195      encoding,
1196      language,
1197      mathstyle,
1198      flags: Some(flags),
1199      // Carry over fields that aren't part of Perl's merge:
1200      mathstylestep: other.mathstylestep.or(self.mathstylestep),
1201      name: other.name.clone().or_else(|| self.name.clone()),
1202      nfss_font: self.nfss_font.clone(),
1203      emph: None,
1204      scripted: None,
1205      fraction: None,
1206      forceseries: if flags & FLAG_FORCE_SERIES != 0 {
1207        Some(true)
1208      } else {
1209        None
1210      },
1211      forcefamily: if flags & FLAG_FORCE_FAMILY != 0 {
1212        Some(true)
1213      } else {
1214        None
1215      },
1216      forceshape: if flags & FLAG_FORCE_SHAPE != 0 {
1217        Some(true)
1218      } else {
1219        None
1220      },
1221      forcebold: None,
1222      scale: None,
1223    };
1224    // Note: Perl's merge() has an optional `specialize` option that is passed
1225    // explicitly (e.g. merge(specialize => $text)). It's NOT keyed on the font name.
1226    // Specialize is called at TBox creation time (tbox.rs) with the actual text content.
1227    // Do NOT call specialize here with the font name — it corrupts font properties
1228    // (e.g. resetting series "bold" to "medium" for font names like "cmb10").
1229    newfont
1230  }
1231
1232  /// Instanciate the font for a particular class of symbols.
1233  /// NOTE: This works in `normal' latex, but probably needs some tunability.
1234  /// Depending on the fonts being used, the allowable combinations may be different.
1235  /// Getting the font right is important, since the author probably
1236  /// thinks of the identity of the symbols according to what they SEE in the printed
1237  /// document.  Even though the markup might seem to indicate something else...
1238  ///
1239  /// Use Unicode properties to determine font merging.
1240  pub fn specialize(&self, text: &str) -> Self {
1241    let mut new = self.clone();
1242    if text.is_empty() {
1243      return new; // ?
1244    }
1245    let (deffamily, defseries, defshape) = self.specialize_defaults();
1246    if LATIN_LETTER_RE.is_match(text) {
1247      // Latin Letter
1248      new.specialize_as_latin_letter();
1249    } else if GREEK_LETTER_RE.is_match(text) {
1250      // Single Greek character?
1251      if UPPER_LETTER_RE.is_match(text) {
1252        // Uppercase
1253        if new.family.is_none() || (new.family.as_ref().unwrap() == "math") {
1254          new.family = Some(deffamily);
1255          if new.shape.is_some() && (new.shape != Some(DEFSHAPE.into())) {
1256            new.shape = Some(defshape); // if ANY shape, must be default
1257          }
1258        }
1259      } else {
1260        // Lowercase
1261        new.specialize_as_lowercase_greek(self, deffamily, defseries);
1262      }
1263    } else if DIGIT_LETTER_RE.is_match(text) {
1264      // Digit
1265      if new.family.is_none() || (new.family.as_ref().unwrap() == "math") {
1266        new.family = Some(deffamily);
1267        new.shape = Some(defshape); // defaults, always.
1268      }
1269    } else {
1270      // Other Symbol
1271      new.family = Some(deffamily);
1272      new.shape = Some(defshape); // defaults, always.
1273      if new.series.is_some() && (new.series.as_ref().unwrap() != DEFSERIES) {
1274        new.series = Some(defseries);
1275      } // defaults, always.
1276    }
1277    new
1278  }
1279
1280  /// Perl `specialize`'s `$deffamily`, `$defseries`, `$defshape`: the font's own value where its `force*` flag
1281  /// holds it, else the default.
1282  fn specialize_defaults(&self) -> (Cow<'static, str>, Cow<'static, str>, Cow<'static, str>) {
1283    let deffamily = if self.forcefamily.unwrap_or(false) {
1284      self.family.clone().unwrap_or_else(|| DEFFAMILY.into())
1285    } else {
1286      DEFFAMILY.into()
1287    };
1288    let defseries = if self.forceseries.unwrap_or(false) {
1289      self.series.clone().unwrap_or_else(|| DEFSERIES.into())
1290    } else {
1291      DEFSERIES.into()
1292    };
1293    let defshape = if self.forceshape.unwrap_or(false) {
1294      self.shape.clone().unwrap_or_else(|| DEFSHAPE.into())
1295    } else {
1296      DEFSHAPE.into()
1297    };
1298    (deffamily, defseries, defshape)
1299  }
1300
1301  /// Perl `specialize`'s Latin-letter rule: italic unless a shape or a family (a math alphabet) is in force.
1302  fn specialize_as_latin_letter(&mut self) {
1303    if self.shape.is_none() && self.family.is_none() {
1304      self.shape = Some("italic".into());
1305    }
1306  }
1307
1308  /// Perl `specialize`'s lowercase-Greek rule: the default family, italic unless a forced shape holds, the default
1309  /// series unless a forced one holds. `orig` is the font before specialization (its `force*` flags).
1310  fn specialize_as_lowercase_greek(
1311    &mut self,
1312    orig: &Font,
1313    deffamily: Cow<'static, str>,
1314    defseries: Cow<'static, str>,
1315  ) {
1316    if self.family.is_none() || (self.family.as_deref() != Some(DEFFAMILY)) {
1317      self.family = Some(deffamily);
1318    }
1319    // Perl: $shape = 'italic' if !$shape || !($flags & $FLAG_FORCE_SHAPE);
1320    if self.shape.is_none() || !orig.forceshape.unwrap_or(false) {
1321      self.shape = Some("italic".into());
1322    }
1323    if self.series.is_some() && (self.series != Some(DEFSERIES.into())) {
1324      self.series = Some(defseries);
1325    }
1326  }
1327
1328  /// `specialize` for a glyph `\DeclareMathSymbol`'d from the math italic symbol font, `letters` (OML `cmm/m/it`,
1329  /// fontmath.ltx:60): a capital Greek letter takes the rule of the fontmath.ltx glyphs of the same class, which
1330  /// Perl's `specialize` encodes — a `\mathalpha` (class 7, variable family) one the Latin letters' (fontmath.ltx:87-138
1331  /// `\DeclareMathSymbol{a}{\mathalpha}{letters}{`a}`): italic unless a math alphabet is in force (`\mathrm`,
1332  /// `\mathbf` upright; `\boldmath`, `\boldsymbol`, `\bm` bold italic), as TeX's class 7 takes `\fam` (tex.web
1333  /// §1151); a `\mathord` (class 0) one the lowercase Greek letters' (fontmath.ltx:175-203 `\DeclareMathSymbol{\alpha}
1334  /// {\mathord}{letters}{"0B}`): italic whatever the alphabet. The capitals follow an alphabet to the same letter
1335  /// because OT1, the alphabets' encoding, holds them at OML's slots "00-"0A; lowercase Greek has no OT1 slot (an
1336  /// alphabet prints a ligature there), so every other glyph keeps `specialize`'s own rule. llncs.cls:379-389,
1337  /// svmult.cls:971-981, svjour3.cls:147-157, fixmath.sty:27-37, amsmath.sty:384-395 (`\varGamma`, class 0).
1338  /// Witnesses 2606.09074 (llncs), 2101.03721 (svjour3), 0812.2480 (svmult), 1002.2350 (fixmath), 2508.05134 (newpxmath
1339  /// `slantedGreek`), 1701.03426 and 2407.01655 (amsmath `\var…`).
1340  pub fn specialize_letters(&self, text: &str, class: LettersClass) -> Self {
1341    if !(GREEK_LETTER_RE.is_match(text) && UPPER_LETTER_RE.is_match(text)) {
1342      return self.specialize(text);
1343    }
1344    let mut new = self.clone();
1345    match class {
1346      LettersClass::Variable => new.specialize_as_latin_letter(),
1347      LettersClass::Fixed => {
1348        let (deffamily, defseries, _) = self.specialize_defaults();
1349        new.specialize_as_lowercase_greek(self, deffamily, defseries);
1350      },
1351    }
1352    new
1353  }
1354
1355  pub fn distance(&self, other: &Font) -> i8 {
1356    let mut distance: i8 = 0;
1357    // Normalize "math" → "serif" for comparison (Perl lines 436-437)
1358    let fam = self
1359      .family
1360      .as_deref()
1361      .map(|f| if f == "math" { "serif" } else { f });
1362    let ofam = other
1363      .family
1364      .as_deref()
1365      .map(|f| if f == "math" { "serif" } else { f });
1366    if is_diff_opt_str(fam, ofam) {
1367      distance += 1;
1368    }
1369    if is_diff_opt_str(self.series.as_deref(), other.series.as_deref()) {
1370      distance += 1;
1371    }
1372    if is_diff_opt_str(self.shape.as_deref(), other.shape.as_deref()) {
1373      distance += 1;
1374    }
1375    if is_diff_f64(self.size, other.size) {
1376      distance += 1;
1377    }
1378    // Color: use reference-style comparison (different Color variant = different).
1379    // Perl's isDiff uses object reference equality: Cmyk(0,0,0,1) ≠ Rgb(0,0,0)
1380    // even though both are visually black.
1381    if is_diff_font_color_ref(self.color.as_ref(), other.color.as_ref()) {
1382      distance += 1;
1383    }
1384    if is_diff_color(self.bg.as_ref(), other.bg.as_ref()) {
1385      distance += 1;
1386    }
1387    if is_diff_opt_str(self.opacity.as_deref(), other.opacity.as_deref()) {
1388      distance += 1;
1389    }
1390    // Perl does NOT count encoding differences
1391    // Perl does NOT count mathstyle differences
1392    if is_diff_opt_str(self.language.as_deref(), other.language.as_deref()) {
1393      distance += 1;
1394    }
1395    // Perl: ($flags & $FLAG_EMPH) ^ ($oflags & $FLAG_EMPH) ? 1 : 0
1396    let flags = self.flags.unwrap_or(0);
1397    let oflags = other.flags.unwrap_or(0);
1398    if (flags & FLAG_EMPH) ^ (oflags & FLAG_EMPH) != 0 {
1399      distance += 1;
1400    }
1401    distance
1402  }
1403
1404  /// This method compares 2 fonts, returning the differences between them.
1405  /// Returns the font attribute string (family/series/shape components that differ
1406  /// from text defaults), joined by spaces. E.g., "italic" for a math font.
1407  /// Used by cancel.sty to capture font state for XML attributes.
1408  pub fn font_attribute_string(&self) -> String {
1409    let mut parts = Vec::new();
1410    if let Some(ref fam) = self.family {
1411      let f = if fam == "math" { "serif" } else { fam.as_ref() };
1412      if f != DEFFAMILY {
1413        parts.push(f.to_string());
1414      }
1415    }
1416    if let Some(ref ser) = self.series
1417      && ser.as_ref() != DEFSERIES
1418    {
1419      parts.push(ser.to_string());
1420    }
1421    if let Some(ref shp) = self.shape
1422      && shp.as_ref() != DEFSHAPE
1423    {
1424      parts.push(shp.to_string());
1425    }
1426    parts.join(" ")
1427  }
1428
1429  /// Noting that the font-related attributes in the schema distill the
1430  /// font properties into fewer attributes (font,fontsize,color,background,opacity),
1431  /// the return value encodes both the attribute changes that would be needed to effect
1432  /// the font change, along with the font properties that differed
1433  /// Namely, the result is a hash keyed on the attribute name and whose value is a FontDiff
1434  ///    value      => "new_attribute_value"
1435  ///    properties => { %fontproperties }
1436  /// or (String, Font)
1437  pub fn relative_to(&self, other: &Font) -> HashMap<String, (String, Font)> {
1438    let family = match self.family {
1439      Some(ref fam) => {
1440        if fam == "math" {
1441          Some(Cow::Borrowed("serif"))
1442        } else {
1443          Some(fam.clone())
1444        }
1445      },
1446      None => None,
1447    };
1448    let other_family = match other.family {
1449      Some(ref fam) => {
1450        if fam == "math" {
1451          Some(Cow::Borrowed("serif"))
1452        } else {
1453          Some(fam.clone())
1454        }
1455      },
1456      None => None,
1457    };
1458    let mut diffs = vec![];
1459    let mut font_properties = Font::default();
1460    if is_diff(family.as_ref(), other_family.as_ref()) {
1461      diffs.push(family.clone().unwrap());
1462      font_properties.family = family;
1463    }
1464    if is_diff(self.series.as_ref(), other.series.as_ref()) {
1465      let series = self.series.clone().unwrap();
1466      diffs.push(series);
1467      font_properties.series.clone_from(&self.series);
1468    }
1469    if is_diff(self.shape.as_ref(), other.shape.as_ref()) {
1470      let shape = self.shape.clone().unwrap();
1471      diffs.push(shape);
1472      font_properties.shape.clone_from(&self.shape);
1473    }
1474    let mut result = HashMap::default();
1475
1476    if !diffs.is_empty() {
1477      let font_value = diffs.join(" ");
1478      result.insert(s!("font"), (font_value, font_properties));
1479    }
1480
1481    if is_diff_f64(self.size.as_ref().copied(), other.size.as_ref().copied()) {
1482      result.insert(
1483        "fontsize".to_string(),
1484        (
1485          relative_font_size(self.size.unwrap(), other.size.unwrap()),
1486          Font {
1487            size: self.size,
1488            ..Font::default()
1489          },
1490        ),
1491      );
1492    }
1493    // Emit color when Color variants differ (reference-style comparison).
1494    // Perl's `ne` treats Cmyk(0,0,0,1) ≠ Rgb(0,0,0) even though both are black.
1495    if is_diff_font_color_ref(self.color.as_ref(), other.color.as_ref()) {
1496      let effective_color = self.color.unwrap_or(DEFCOLOR);
1497      result.insert(
1498        "color".to_string(),
1499        (effective_color.to_attribute(), Font {
1500          color: Some(effective_color),
1501          ..Font::default()
1502        }),
1503      );
1504    }
1505    if is_diff_color(self.bg.as_ref(), other.bg.as_ref()) {
1506      result.insert(
1507        "backgroundcolor".to_string(),
1508        (self.bg.as_ref().unwrap().to_attribute(), Font {
1509          bg: self.bg,
1510          ..Font::default()
1511        }),
1512      );
1513    }
1514    if is_diff(self.opacity.as_ref(), other.opacity.as_ref()) {
1515      result.insert(
1516        "opacity".to_string(),
1517        (self.opacity.as_ref().unwrap().to_string(), Font {
1518          opacity: self.opacity.clone(),
1519          ..Font::default()
1520        }),
1521      );
1522    }
1523    // #638: the font `encoding` is a FontMap-lookup key consumed DURING digestion
1524    // (unicode decoding), not a presentation property — it is meaningless as an
1525    // output attribute and no ltx element even declares it, so Perl emits no
1526    // `@encoding` anywhere. Emitting it here only ever surfaced (spuriously) on a
1527    // foreign `xhtml:*` element whose `attribute *` wildcard accepts anything.
1528    // Omit it from the relativized attribute set entirely (Perl `Font.pm` keeps
1529    // the analogous line, but the value never reaches real output there).
1530    if is_diff(self.language.as_ref(), other.language.as_ref()) {
1531      result.insert(
1532        "xml:lang".to_string(),
1533        (self.language.as_ref().unwrap().to_string(), Font {
1534          language: self.language.clone(),
1535          ..Font::default()
1536        }),
1537      );
1538    }
1539    // Emph: (!$mstyle && $flags && ($flags & $FLAG_EMPH) && (!$oflags || !($oflags & $FLAG_EMPH))
1540    let flags = self.flags.unwrap_or(0);
1541    let oflags = other.flags.unwrap_or(0);
1542    if self.mathstyle.is_none()
1543      && flags != 0
1544      && (flags & FLAG_EMPH) != 0
1545      && (oflags == 0 || (oflags & FLAG_EMPH) == 0)
1546    {
1547      result.insert(
1548        "element".to_string(),
1549        ("ltx:emph".to_string(), Font::default()),
1550      );
1551    }
1552    // We do NOT want mathstyle showing up automatically in the attributes
1553    result
1554  }
1555
1556  pub fn purestyle_changes(&self, other: &Font) -> Font {
1557    let mathstyle = self.get_mathstyle();
1558    let othermathstyle = other.get_mathstyle();
1559    let othercolor = other.get_color();
1560    let mut changes = Font {
1561      scale: Some(other.get_size().unwrap() / self.get_size().unwrap()),
1562      bg: other.bg,
1563      opacity: other.opacity.clone(), // should multiply or replace?
1564      ..Font::default()
1565    };
1566    if is_diff_font_color(othercolor, Some(&DEFCOLOR)) {
1567      changes.color = Some(othercolor.copied().unwrap_or(DEFCOLOR));
1568    }
1569
1570    if let Some(ms) = mathstyle
1571      && let Some(os) = othermathstyle
1572    {
1573      let ms_str: &str = ms;
1574      let os_str: &str = os;
1575      changes.mathstylestep = Some(*MATH_STYLE_STEP.get(ms_str).unwrap().get(os_str).unwrap());
1576    }
1577    changes
1578  }
1579
1580  /// This font with the NFSS font a `\font` identifier replaced (`nfss_font`) back in force: its
1581  /// family, series, shape, size and encoding, no `name`.
1582  fn nfss_restored(&self) -> Font {
1583    let mut base = self.clone();
1584    base.name = None;
1585    base.nfss_font = None;
1586    if let Some(nfss) = &self.nfss_font {
1587      base.family = nfss.family.clone();
1588      base.series = nfss.series.clone();
1589      base.shape = nfss.shape.clone();
1590      base.size = nfss.size;
1591      base.encoding = nfss.encoding.clone();
1592    }
1593    base
1594  }
1595
1596  /// The TFM a character of this font is measured from: a font loaded by name (`\font`) whose
1597  /// family has no standard metric, while it is still that font's family and encoding (a later
1598  /// font selection ends it, `merge_ref`). Fonts with a standard metric keep Perl's metric
1599  /// (`get_metric`; KPE #408, witness 2605.02221).
1600  pub fn measuring_tfm(&self) -> Option<Rc<tfm::Tfm>> {
1601    let name = self.name.as_deref()?;
1602    let family = self.family.as_deref().unwrap_or("serif");
1603    let series = self.series.as_deref().unwrap_or("medium");
1604    let shape = self.shape.as_deref().unwrap_or("upright");
1605    if lookup_metric_name(family, series, shape).is_some() {
1606      return None;
1607    }
1608    let named = NAMED_FONT_CLASS.with(|cache| {
1609      cache
1610        .borrow_mut()
1611        .entry(name.to_string())
1612        .or_insert_with(|| decode_fontname(name, None, None).map(|f| (f.family, f.encoding)))
1613        .clone()
1614    })?;
1615    if named != (self.family.clone(), self.encoding.clone()) {
1616      return None;
1617    }
1618    tfm::tfm_for(name)
1619  }
1620
1621  /// Find a Font Metric corresponding to this font's family_series_shape_size
1622  /// that contains the given `char`, if given.
1623  /// Try to find a fallback metric if `char` is not in the current Font.
1624  /// Perl: getMetric
1625  pub fn get_metric(&self, c_opt: Option<char>) -> &MetricData {
1626    let family = self.family.as_deref().unwrap_or("serif");
1627    let series = self.series.as_deref().unwrap_or("medium");
1628    let shape = self.shape.as_deref().unwrap_or("upright");
1629    let size = self.size.unwrap_or_else(defsize) as i64;
1630    // Stack buffer for char→&str lookup key, reused across paths. Avoids
1631    // one String allocation per character per get_metric call (which is
1632    // called per-character inside compute_string_size).
1633    let mut ch_buf = [0u8; 4];
1634    let ch_key = c_opt.map(|c| c.encode_utf8(&mut ch_buf) as &str);
1635    if let Some(name) = lookup_metric_name(family, series, shape) {
1636      let fullname = format!("{name}{size}");
1637      if let Some(metric) = STDMETRICS.get(fullname.as_str())
1638        && ch_key.is_none_or(|k| metric.sizes.contains_key(k))
1639      {
1640        return metric;
1641      }
1642      // Try base name fallback
1643      let metric = get_metric_for_name(name);
1644      if ch_key.is_none_or(|k| metric.sizes.contains_key(k)) {
1645        return metric;
1646      }
1647    }
1648    // Look for a fallback metric if char given
1649    if let Some(k) = ch_key {
1650      for name in METRIC_FALLBACKS {
1651        let fullname = format!("{name}{size}");
1652        let metric = STDMETRICS
1653          .get(fullname.as_str())
1654          .unwrap_or_else(|| get_metric_for_name(name));
1655        if metric.sizes.contains_key(k) {
1656          return metric;
1657        }
1658      }
1659    }
1660    get_metric_for_name("cmr")
1661  }
1662
1663  pub fn get_em_width(&self) -> i64 {
1664    let size = self.get_size().unwrap_or_else(defsize);
1665    let m = self.get_metric(None);
1666    (size * m.emwidth).trunc() as i64
1667  }
1668  pub fn get_ex_height(&self) -> i64 {
1669    let size = self.get_size().unwrap_or_else(defsize);
1670    let m = self.get_metric(None);
1671    (size * m.exheight).trunc() as i64
1672  }
1673  pub fn get_mu_width(&self) -> i64 {
1674    let size = self.get_size().unwrap_or_else(defsize);
1675    let m = self.get_metric(None);
1676    (size * m.emwidth / 18.0).trunc() as i64
1677  }
1678
1679  pub fn compute_string_size(
1680    &self,
1681    text: &str,
1682    _options: SymHashMap<Stored>,
1683  ) -> (Dimension, Dimension, Dimension) {
1684    if text.is_empty()
1685      || self
1686        .get_family()
1687        .map(|fam| fam == "nullfont")
1688        .unwrap_or(false)
1689    {
1690      return (
1691        Dimension::default(),
1692        Dimension::default(),
1693        Dimension::default(),
1694      );
1695    }
1696    let size = self.get_size().unwrap_or_else(defsize);
1697    let ismath = self.get_family().map(|fam| fam == "math").unwrap_or(false);
1698    let (mut w, mut h, mut d) = (0, 0, 0);
1699    // Iterate via Peekable — no intermediate Vec<char> allocation,
1700    // and we get O(1) lookahead for kerning between consecutive chars.
1701    let mut chars_iter = text.chars().peekable();
1702    // Stack buffers for char→&str and char+char→&str lookups, avoiding
1703    // String::to_string() + String::format!() heap allocations inside
1704    // the per-character hot loop. encode_utf8 writes directly to the
1705    // buffer and returns a borrowed &str slice — no allocation.
1706    let mut ch_buf = [0u8; 4];
1707    let mut kern_buf = [0u8; 8];
1708    while let Some(ch) = chars_iter.next() {
1709      let metric = self.get_metric(Some(ch));
1710      let ch_key = ch.encode_utf8(&mut ch_buf);
1711      let entry_opt = metric.sizes.get(ch_key);
1712      let (cw, ch_sz, cd, ci) = if let Some(entry) = entry_opt {
1713        *entry
1714      } else {
1715        (0.75 * UNITY_F64, 0.7 * UNITY_F64, 0.2 * UNITY_F64, 0.0)
1716      };
1717      w += (cw * size).trunc() as i64;
1718      // Kerning: check kern between this char and next.
1719      if let Some(&next_ch) = chars_iter.peek() {
1720        let first_len = ch.encode_utf8(&mut kern_buf).len();
1721        let second_len = next_ch.encode_utf8(&mut kern_buf[first_len..]).len();
1722        let kern_key = std::str::from_utf8(&kern_buf[..first_len + second_len]).unwrap();
1723        if let Some(kern) = metric.kerns.get(kern_key) {
1724          w += (size * kern).trunc() as i64;
1725        }
1726      }
1727      // Italic correction in math
1728      if ismath && ci != 0.0 {
1729        w += (size * ci).trunc() as i64;
1730      }
1731      h = max(h, (ch_sz * size).trunc() as i64);
1732      d = max(d, (cd * size).trunc() as i64);
1733    }
1734    // The 1 is so that any actual glyph appears to be non-empty.
1735    // This is presumably only necessary to deal with the flawed emptiness heiristics in Alignment?
1736    if w == 0 {
1737      w = 1;
1738    }
1739    (Dimension::new(w), Dimension::new(h), Dimension::new(d))
1740  }
1741
1742  /// Get nominal width, height base ?
1743  /// Probably should be using data from FontMetric ???
1744  pub fn get_nominal_size(&self) -> (Dimension, Dimension, Dimension) {
1745    let size = self.get_size().unwrap_or_else(defsize);
1746    let u = size * UNITY_F64;
1747    (
1748      Dimension::new_f64(0.75 * u),
1749      Dimension::new_f64(0.7 * u),
1750      Dimension::new_f64(0.2 * u),
1751    )
1752  }
1753
1754  // Here's where I avoid trying to emulate Knuth's line-breaking...
1755  // Mostly for List & Whatsit: compute the size of a list of boxes.
1756  // Options _SHOULD_ include:
1757  //   width:  if given, pretend to simulate line breaking to that width
1758  //   height,depth : ?
1759  //   vattach : top, bottom, center, baseline (...?) affects how the height & depth are
1760  //      allocated when there are multiple lines.
1761  //   layout : horizontal or vertical !!!
1762  // Boxes that arent a Core Box, List, Whatsit or a string are IGNORED
1763  //
1764  // The big problem with width is to have it propogate down from where
1765  // it may have been specified to the actual nested box that will get wrapped!
1766  // Try to mask this (temporarily) by unlisting, and (pretending to ) breaking up too wide items
1767  //
1768  // Another issue; SVG needs (sometimes) real sizes, even if the programmer
1769  // set some dimensions to 0 (eg.)   We may need to distinguish & store
1770  // requested vs real sizes?
1771  /// Perl: Font.pm sub computeBoxesSize (L635-680)
1772  /// Compute the size of a List of boxes, dispatching to helpers based on layout mode.
1773  pub fn compute_boxes_size(
1774    &self,
1775    boxes: &[Digested],
1776    options: SymHashMap<Stored>,
1777  ) -> Result<(Dimension, Dimension, Dimension)> {
1778    // Perl L646-647: `elsif ($ref =~ /^LaTeXML::Core::(?:Box|Whatsit|Alignment)$/) {
1779    // return $boxes->getSize; }` — a single bare Box/Whatsit/Alignment (NOT a
1780    // List) returns its getSize directly, short-circuiting ahead of the
1781    // List/split_words logic. This is essential for an isSpace box carrying an
1782    // explicit height/depth (e.g. `\phantom`'s XMHint): split_words keeps only
1783    // its width as inter-word space and discards height/depth, but getSize honors
1784    // the full width/height/depth. In Perl the dispatch is on the type of the
1785    // measured object (a bare-box body, not a List); a single-element slice here
1786    // is the faithful analogue, since Perl's `List()` returns a lone box of the
1787    // list's mode itself (List.pm:41-44). `List::compute_size` floors a
1788    // horizontal list's height and depth after it, as `hpack` does.
1789    if let [single] = boxes
1790      && !matches!(single.data(), DigestedData::List(_))
1791    {
1792      let mut bx_clone = single.clone();
1793      let (w, h, d, ..) = bx_clone.get_size(None)?;
1794      return Ok((w, h, d));
1795    }
1796    // Perl L638: my $mode = $boxes->getProperty('mode') || 'restricted_horizontal';
1797    let mode_str = match options.get("mode") {
1798      Some(Stored::String(s)) => arena::with(*s, |s| s.to_string()),
1799      _ => "restricted_horizontal".to_string(),
1800    };
1801    // Perl: $vattach = $boxes->getProperty('vattach') || $options{vattach} || 'baseline'
1802    let vattach = match options.get("vattach") {
1803      Some(Stored::String(s)) => arena::with(*s, |s| s.to_string()),
1804      _ => "baseline".to_string(),
1805    };
1806    // Perl #2798: `elsif (my $width = ($mode =~ /horizontal$/) && $boxes->getProperty('width'))`
1807    // — a horizontal list is formatted as a paragraph IFF an explicit width is
1808    // supplied (recorded by S4's repack_horizontal). NO `\hsize` fallback: a
1809    // horizontal List without a width property is restricted_horizontal (a single
1810    // line, no wrapping), matching Perl.
1811    let para_width: Option<i64> = if mode_str.ends_with("horizontal") {
1812      match options.get("width") {
1813        Some(Stored::Dimension(d)) => Some(d.value_of()),
1814        Some(Stored::Int(i)) => Some(*i),
1815        _ => None,
1816      }
1817    } else {
1818      None
1819    };
1820    // Perl #2798: baseline (sp) — from List property (S4) / option, default 12pt.
1821    let baseline: i64 = match options.get("baseline") {
1822      Some(Stored::Dimension(d)) => d.value_of(),
1823      Some(Stored::Int(i)) => *i,
1824      _ => 12 * UNITY,
1825    };
1826    let mut maxwidth: i64 = 0;
1827    // Perl #2798: lines are now [baseline, wd, ht, dp] (per-line baseline; -1 = no
1828    // inter-line adjustment, e.g. \vskip / \hrule).
1829    let mut lines: Vec<[i64; 4]> = Vec::new();
1830    if mode_str.ends_with("vertical") {
1831      // Perl: For vertical, ALL boxes are lines. (Rust makes the box-list match
1832      // Perl's structure BEFORE this point: a text-mode `{...}` group that
1833      // breaks a paragraph repacks the outer paragraph at digestion — see
1834      // `tex_box.rs` `{` primitive R2 / OXIDIZED_DESIGN #100 — so no run of loose
1835      // characters ever reaches here to be mis-counted one-line-per-glyph.)
1836      for bx in boxes {
1837        // A penalty, like glue, makes a top-attached box 0pt high when it comes first (tex.web §1087).
1838        if bx.get_property_bool("isPenalty") {
1839          if lines.is_empty() && vattach == "top" {
1840            lines.push([-1, 0, 0, 0]);
1841          }
1842          continue;
1843        }
1844        if bx.has_property("isEmpty") {
1845          continue;
1846        }
1847        // Perl: a horizontal sub-List WITH a width is formatted as a paragraph.
1848        if matches!(bx.data(), DigestedData::List(_))
1849          && bx
1850            .get_property("mode")
1851            .map(|v| v.to_string())
1852            .unwrap_or_default()
1853            == "horizontal"
1854          && let Some(w) = bx.get_property("width").and_then(|v| match &*v {
1855            Stored::Dimension(d) => Some(d.value_of()),
1856            Stored::Int(i) => Some(*i),
1857            _ => None,
1858          })
1859        {
1860          if w > maxwidth {
1861            maxwidth = w;
1862          }
1863          let sub_baseline = bx
1864            .get_property("baseline")
1865            .and_then(|v| match &*v {
1866              Stored::Dimension(d) => Some(d.value_of()),
1867              Stored::Int(i) => Some(*i),
1868              _ => None,
1869            })
1870            .unwrap_or(baseline);
1871          let items = bx.unlist();
1872          if items.is_empty() {
1873            // A paragraph's empty line (stomach.rs `end_graf`, `\leavevmode\par`): no height, but a line on the
1874            // list, so the next box is a `\baselineskip` below it (tex.web §1096).
1875            lines.push([sub_baseline, w, 0, 0]);
1876          } else {
1877            lines.extend(self.linebreak_paragraph(&items, w, sub_baseline)?);
1878          }
1879          continue;
1880        }
1881        // Perl: single box → one line, with baseline (or -1 for vskip/rule).
1882        // DIVERGENCE from Perl #2798 (upstream candidate): Perl folds vskips
1883        // and rules into one `-1` flag and RESETS prevdepth for both, so any
1884        // glue item between lines silently disables \baselineskip accounting
1885        // — a stack of N verbatim lines interleaved with fancyvrb's interline
1886        // vspace measures as Σ(h+d) ≈ N×6pt instead of N×\baselineskip
1887        // (witness 2605.00468: 49-line Prompt boxes budgeted at half their
1888        // TeX height; content spilled through every following box). TeX truth
1889        // (tex.web vpack): \prevdepth is TRANSPARENT to glue — only a BOX
1890        // updates it (to its depth), and only \hrule disables it (sentinel
1891        // \prevdepth = -1000pt). Encode vskip as -1 (transparent) and rule
1892        // as -2 (reset) so the stack can honor both.
1893        let (w, h, d) = self.compute_boxes_size_box(bx)?;
1894        let bs = if bx.get_property_bool("isHorizontalRule") {
1895          -2
1896        } else if bx.get_property_bool("isVerticalSpace") {
1897          -1
1898        } else {
1899          baseline
1900        };
1901        // A leading skip or kern sets a top-attached box's height to 0pt even when it is empty (tex.web §1087):
1902        // `\vtop{\kern0pt …}`, as `\vspace{0pt}` atop a `[t]` minipage, puts the reference point at the top.
1903        let leading_skip = bs == -1 && lines.is_empty() && vattach == "top";
1904        if w != 0 || h != 0 || d != 0 || leading_skip {
1905          lines.push([bs, w, h, d]);
1906        }
1907      }
1908    } else if let Some(w) = para_width {
1909      // Perl: proper paragraph — flatten, split into words, break into lines.
1910      if w > maxwidth {
1911        maxwidth = w;
1912      }
1913      let flat: Vec<&Digested> = boxes
1914        .iter()
1915        .filter(|b| !b.has_property("isEmpty"))
1916        .collect();
1917      let flat_owned: Vec<Digested> = flat.into_iter().cloned().collect();
1918      lines = self.linebreak_paragraph(&flat_owned, w, baseline)?;
1919    } else {
1920      // Perl: restricted_horizontal or math — one line, no wrapping.
1921      let filtered: Vec<&Digested> = boxes
1922        .iter()
1923        .filter(|b| !b.has_property("isEmpty"))
1924        .collect();
1925      let words = self.compute_boxes_size_words(&filtered)?;
1926      lines = Self::compute_boxes_size_lines(None, baseline, &words);
1927    }
1928    // Perl: stack up the multiple lines; mathaxis = size/4.
1929    let size = self.get_size().unwrap_or_else(defsize) as i64;
1930    let mathaxis = size * UNITY / 4;
1931    static SIZE_TRACE: LazyLock<bool> = LazyLock::new(|| std::env::var("LXML_SIZE_TRACE").is_ok());
1932    if *SIZE_TRACE {
1933      eprintln!(
1934        "SIZE mode={mode_str} vattach={vattach} baseline={} nboxes={} lines={:?}",
1935        baseline as f64 / 65536.0,
1936        boxes.len(),
1937        lines
1938          .iter()
1939          .map(|l| [
1940            l[0] as f64 / 65536.0,
1941            l[1] as f64 / 65536.0,
1942            l[2] as f64 / 65536.0,
1943            l[3] as f64 / 65536.0
1944          ])
1945          .collect::<Vec<_>>()
1946      );
1947    }
1948    let skip_option = |key: &str| match options.get(key) {
1949      Some(Stored::Dimension(d)) => Some(d.value_of()),
1950      Some(Stored::Int(i)) => Some(*i),
1951      _ => None,
1952    };
1953    let interline = (skip_option("lineskip"), skip_option("lineskiplimit"));
1954    let (mut wd, mut ht, mut dp) =
1955      Self::compute_boxes_size_stack(&vattach, mathaxis, &lines, interline);
1956    // Perl: $wd = $maxwidth if $wd && $maxwidth (set to fill width, unless empty). Under `natural_width` the
1957    // widest line's own width instead, as varwidth.sty's `\@vwid@measure` re-measures each line.
1958    if wd != 0 && maxwidth != 0 && !matches!(options.get("natural_width"), Some(Stored::Bool(true)))
1959    {
1960      wd = maxwidth;
1961    }
1962    // Perl: divide up totalheight, if requested.
1963    if let Some(th) = options.get("totalheight").and_then(|v| match v {
1964      Stored::Dimension(d) => Some(d.value_of()),
1965      Stored::Int(i) => Some(*i),
1966      _ => None,
1967    }) {
1968      let diff = th - ht - dp;
1969      if diff > 0 {
1970        match vattach.as_str() {
1971          "bottom" => ht += diff,
1972          "middle" => {
1973            ht += diff / 2;
1974            dp += diff / 2;
1975          },
1976          _ => dp += diff,
1977        }
1978      }
1979    }
1980    Ok((Dimension::new(wd), Dimension::new(ht), Dimension::new(dp)))
1981  }
1982
1983  /// Perl #2798: linebreak_paragraph — format a horizontal list (with width) as
1984  /// a paragraph: flatten nested horizontal Lists + sizing-flattenable Whatsits,
1985  /// split into words, then break into lines. Returns [baseline, wd, ht, dp] lines.
1986  fn linebreak_paragraph(
1987    &self,
1988    boxes: &[Digested],
1989    width: i64,
1990    baseline: i64,
1991  ) -> Result<Vec<[i64; 4]>> {
1992    let flat = Self::flatten_paragraph(boxes);
1993    let flat_refs: Vec<&Digested> = flat.iter().collect();
1994    let words = self.compute_boxes_size_words(&flat_refs)?;
1995    Ok(Self::compute_boxes_size_lines(
1996      Some(width),
1997      baseline,
1998      &words,
1999    ))
2000  }
2001
2002  /// Perl #2798: flatten_paragraph — open up contained horizontal Lists, and any
2003  /// Whatsits that format AS IF embedded paragraph material (e.g. `\emph`), so
2004  /// they participate in line-breaking.
2005  fn flatten_paragraph(boxes: &[Digested]) -> Vec<Digested> {
2006    let mut queue: std::collections::VecDeque<Digested> = boxes.iter().cloned().collect();
2007    let mut out: Vec<Digested> = Vec::new();
2008    while let Some(bx) = queue.pop_front() {
2009      // A finished paragraph stays one unit (see `is_finished_paragraph`).
2010      if matches!(bx.data(), DigestedData::List(_))
2011        && !is_finished_paragraph(&bx)
2012        && bx
2013          .get_property("mode")
2014          .map(|v| v.to_string())
2015          .unwrap_or_default()
2016          == "horizontal"
2017      {
2018        for ib in bx.unlist().into_iter().rev() {
2019          queue.push_front(ib);
2020        }
2021      } else if matches!(bx.data(), DigestedData::Whatsit(_))
2022        && let Some(repl) = flatten_for_sizing(&bx)
2023      {
2024        for ib in repl.into_iter().rev() {
2025          queue.push_front(ib);
2026        }
2027      } else {
2028        out.push(bx);
2029      }
2030    }
2031    out
2032  }
2033
2034  /// Perl: Font.pm sub computeBoxesSize_box (L683-702)
2035  /// Compute the size of a single box, returning (w, h, d) in sp.
2036  fn compute_boxes_size_box(&self, bx: &Digested) -> Result<(i64, i64, i64)> {
2037    // Clone to avoid caching side effects on the original box
2038    let mut bx_clone = bx.clone();
2039    let (w, h, d, ..) = bx_clone.get_size(None)?;
2040    Ok((w.value_of(), h.value_of(), d.value_of()))
2041  }
2042
2043  /// Whether `bx` carries a nonzero `height` or `depth` property, as a phantom's `after_digest` sets them.
2044  fn declares_height_or_depth(bx: &Digested) -> bool {
2045    ["height", "depth"].iter().any(|key| {
2046      bx.get_property(key)
2047        .is_some_and(|v| matches!(&*v, Stored::Dimension(d) if d.value_of() != 0))
2048    })
2049  }
2050
2051  /// Perl: Font.pm sub computeBoxesSize_words (L705-746)
2052  /// Compute a list of sizes of space-delimited "words" within a NON-vertical list.
2053  /// Returns Vec of [prevspace, wd, ht, dp] where prevspace=-1 means line break.
2054  fn compute_boxes_size_words(&self, boxes: &[&Digested]) -> Result<Vec<[f64; 4]>> {
2055    let mut words: Vec<[f64; 4]> = Vec::new();
2056    let mut prevbox: Option<&Digested> = None;
2057    let mut prevspace: f64 = 0.0;
2058    // Perl L711: my $size = int($self->getSize || DEFSIZE() || 10);
2059    let size = self.get_size().unwrap_or_else(defsize) as i64;
2060    let (mut wd, mut ht, mut dp): (f64, i64, i64) = (0.0, 0, 0);
2061    for bx in boxes {
2062      let (w, h, d) = self.compute_boxes_size_box(bx)?;
2063      // Perl L716-721: Check for possible line-break points
2064      if bx.get_property_bool("isBreak") {
2065        // Perl: vertical space (isBreak + isVerticalSpace) contributes height
2066        // even though it acts as a line break. Include its h/d in the word
2067        // so alignment row spacing accounts for \noalign{\vskip X}.
2068        if bx.get_property_bool("isVerticalSpace") {
2069          ht = max(ht, h);
2070          dp = max(dp, d);
2071        }
2072        if wd != 0.0 || ht != 0 || dp != 0 || prevspace > 0.0 {
2073          words.push([prevspace, wd, ht as f64, dp as f64]);
2074          wd = 0.0;
2075          ht = 0;
2076          dp = 0;
2077          prevspace = -1.0;
2078        } else {
2079          prevspace = -1.0;
2080        }
2081      }
2082      // Perl L723-728: isSpace (but not isVerticalSpace) — word boundary. A space-like box declaring a height or depth
2083      // (`\phantom`, `\vphantom`, `\mathstrut`: latex.ltx `\finph@nt` boxes) is a box TeX sets in the word, so it falls
2084      // to the word below (Perl kept its width alone: KNOWN_PERL_ERRORS #1327; xy's `*[o]{\phantom{s}}` circle,
2085      // 1210.5701). An interword space's measured size is no declaration: glue has none.
2086      else if bx.get_property_bool("isSpace")
2087        && !bx.get_property_bool("isVerticalSpace")
2088        && !Self::declares_height_or_depth(bx)
2089      {
2090        if wd != 0.0 || ht != 0 || dp != 0 || prevspace < 0.0 {
2091          words.push([prevspace, wd, ht as f64, dp as f64]);
2092          wd = 0.0;
2093          ht = 0;
2094          dp = 0;
2095          prevspace = w as f64;
2096        } else {
2097          prevspace += w as f64;
2098        }
2099      }
2100      // A finished paragraph inside the line (see `is_finished_paragraph`) takes lines of its own:
2101      // it ends the word before it, and a break follows it; an empty one (a `\par` with nothing
2102      // before it, as a tikz node's text opens) makes no line.
2103      else if is_finished_paragraph(bx) {
2104        if wd != 0.0 || ht != 0 || dp != 0 {
2105          words.push([prevspace, wd, ht as f64, dp as f64]);
2106        }
2107        if h != 0 || d != 0 {
2108          words.push([-1.0, w as f64, h as f64, d as f64]);
2109        }
2110        wd = 0.0;
2111        ht = 0;
2112        dp = 0;
2113        prevspace = -1.0;
2114      }
2115      // Perl #2798: an ideographic (CJK) char is itself a word.
2116      else if bx.get_property_bool("isIdeographic") {
2117        if wd != 0.0 {
2118          words.push([prevspace, wd, ht as f64, dp as f64]);
2119        }
2120        words.push([0.0, w as f64, h as f64, d as f64]);
2121        wd = 0.0;
2122        ht = 0;
2123        dp = 0;
2124        prevspace = 0.0;
2125      }
2126      // Perl L729-741: Else accumulate into "word"
2127      else {
2128        wd += w as f64;
2129        ht = max(ht, h);
2130        dp = max(dp, d);
2131        // Perl L734-741: Kern HACK for lists of individual Box's
2132        if let Some(pb) = prevbox
2133          && matches!(pb.data(), DigestedData::TBox(_))
2134          && matches!(bx.data(), DigestedData::TBox(_))
2135        {
2136          let prevchar = pb.get_string()?.chars().last();
2137          let curchar = bx.get_string()?.chars().next();
2138          let metric = self.get_metric(curchar);
2139          // Perl L738-739: math bearing
2140          if let Some(family) = self.get_family()
2141            && family == "math"
2142          {
2143            wd += self.math_bearing(bx, pb);
2144          }
2145          // Perl L740-741: kerning
2146          if let Some(prevc) = prevchar
2147            && let Some(curc) = curchar
2148          {
2149            let kern_key = String::from(prevc) + &String::from(curc);
2150            if let Some(kern) = metric.kerns.get(kern_key.as_str()) {
2151              wd += size as f64 * kern;
2152            }
2153          }
2154        }
2155      }
2156      // Perl L743: $prevbox = $box
2157      prevbox = Some(bx);
2158    }
2159    // Perl L744-745: be sure to get last bit
2160    if wd != 0.0 || ht != 0 || dp != 0 || prevspace != 0.0 {
2161      words.push([prevspace, wd, ht as f64, dp as f64]);
2162    }
2163    Ok(words)
2164  }
2165
2166  /// Perl #2798: collect_lines — break words into lines per `wrapwidth` (if any)
2167  /// or explicit breaks. Each line is `[baseline, wd, ht, dp]`; the per-line
2168  /// `baseline` drives inter-line spacing in `compute_boxes_size_stack`.
2169  fn compute_boxes_size_lines(
2170    wrapwidth: Option<i64>,
2171    baseline: i64,
2172    words: &[[f64; 4]],
2173  ) -> Vec<[i64; 4]> {
2174    let mut lines: Vec<[i64; 4]> = Vec::new();
2175    let fuzz = UNITY as f64; // 1pt
2176    let (mut wd, mut ht, mut dp): (f64, i64, i64) = (0.0, 0, 0);
2177    for item in words {
2178      let (space, w, h, d) = (item[0], item[1], item[2] as i64, item[3] as i64);
2179      // Forced linebreak (space == -1) or wrapped linebreak.
2180      if space == -1.0 || wrapwidth.is_some_and(|ww| wd + space * 0.5 + w > ww as f64 + fuzz) {
2181        if wd != 0.0 {
2182          lines.push([baseline, kround(wd), ht, dp]);
2183        }
2184        wd = w;
2185        ht = h;
2186        dp = d;
2187      } else {
2188        wd += space + w;
2189        ht = max(ht, h);
2190        dp = max(dp, d);
2191      }
2192    }
2193    if wd != 0.0 || ht != 0 || dp != 0 {
2194      lines.push([baseline, kround(wd), ht, dp]);
2195    }
2196    lines
2197  }
2198
2199  /// Perl #2798: stack_lines — sum a stack of `[baseline, wd, ht, dp]` lines:
2200  /// `wd` is the max, inter-line spacing uses each line's `baseline` (`bs < 0` =
2201  /// no adjustment), and `ht`/`dp` are split per `vattach` (`mathaxis` = size/4).
2202  fn compute_boxes_size_stack(
2203    vattach: &str,
2204    mathaxis: i64,
2205    lines: &[[i64; 4]],
2206    (lineskip, lineskiplimit): (Option<i64>, Option<i64>),
2207  ) -> (i64, i64, i64) {
2208    let nlines = lines.len();
2209    if nlines == 0 {
2210      return (0, 0, 0);
2211    }
2212    // tex.web §1087: a `\vtop` is as high as its first item when that is a box or rule, else 0pt high — a leading
2213    // skip, kern or penalty goes into its depth (`\vtop{\vskip5pt\hbox{A}}` is 0pt high, 11.83pt deep).
2214    let leading_skip = vattach == "top" && lines[0][0] == -1;
2215    if nlines == 1 && !leading_skip {
2216      let [_bs, w, h, d] = lines[0];
2217      return (w, h, d);
2218    }
2219    // Perl: $lineskip = lookupDefinition('\lineskip')->valueOf->valueOf — the box's own when it recorded them.
2220    let register = |cs: &str| {
2221      lookup_definition(&T_CS!(cs))
2222        .ok()
2223        .flatten()
2224        .and_then(|def| def.value_of(Vec::new()))
2225        .map(|v| v.value_of())
2226        .unwrap_or(0)
2227    };
2228    let lineskip = lineskip.unwrap_or_else(|| register("\\lineskip"));
2229    // A list that recorded no limit is stacked with LaTeX's 0pt, not the limit in force where it is measured: a
2230    // minipage measured inside an `\offinterlineskip` group (`\maxdimen`) lost its interline glue
2231    // (OXIDIZED_DESIGN_DIVERGENCES #421).
2232    let lineskiplimit = lineskiplimit.unwrap_or(0);
2233    let mut wd: i64 = 0;
2234    let mut prevdepth: i64 = -99999;
2235    let mut th: i64 = 0;
2236    for line in lines {
2237      let [bs, w, h, d] = *line;
2238      wd = max(w, wd);
2239      th += h + d;
2240      // tex.web §679: `\baselineskip` less the depth above and the height below, `\lineskip` when that is under
2241      // `\lineskiplimit`.
2242      if prevdepth >= 0 && bs >= 0 {
2243        let gap = bs - prevdepth - h;
2244        th += if gap >= lineskiplimit { gap } else { lineskip };
2245      }
2246      // TeX vpack \prevdepth discipline (divergence from Perl #2798 — see
2247      // the vertical branch above): boxes set prevdepth to their depth;
2248      // glue (bs == -1) is TRANSPARENT (prevdepth unchanged, so the next
2249      // box still receives \baselineskip accounting across the skip);
2250      // rules (bs == -2) disable it (TeX's \prevdepth = -1000pt sentinel).
2251      prevdepth = if bs >= 0 {
2252        d
2253      } else if bs == -1 {
2254        prevdepth
2255      } else {
2256        -99999
2257      };
2258    }
2259    let (ht, dp) = match vattach {
2260      "middle" => (th / 2 + mathaxis, th / 2 - mathaxis),
2261      "bottom" => {
2262        let d = lines[nlines - 1][3];
2263        (th - d, d)
2264      },
2265      _ if leading_skip => (0, th),
2266      // else (baseline / top): align to baseline of top row.
2267      _ => {
2268        let h = lines[0][2];
2269        (h, th - h)
2270      },
2271    };
2272    (wd, ht, dp)
2273  }
2274}
2275
2276/// Perl #2798: `Whatsit->flattenForSizing` — a horizontal Whatsit whose sizer is
2277/// a pure `#arg`/`#prop` reference can be flattened so its content participates
2278/// in paragraph line-breaking (e.g. `\emph`). STUB: returns `None` (no
2279/// flattening) for now — refine to parse the sizer spec. None of the current
2280/// sizing fixtures depend on this; only `\emph`-style line-wrapping differs.
2281fn flatten_for_sizing(_w: &Digested) -> Option<Vec<Digested>> { None }
2282
2283fn is_diff(x: Option<&Cow<str>>, y: Option<&Cow<str>>) -> bool {
2284  x.is_some() && (y.is_none() || (x != y))
2285}
2286
2287fn is_diff_opt_str(x: Option<&str>, y: Option<&str>) -> bool {
2288  x.is_some() && (y.is_none() || (x != y))
2289}
2290
2291fn is_diff_f64(x: Option<f64>, y: Option<f64>) -> bool { x.is_some() && (y.is_none() || (x != y)) }
2292
2293fn is_diff_color(x: Option<&Color>, y: Option<&Color>) -> bool {
2294  x.is_some() && (y.is_none() || (x != y))
2295}
2296
2297/// Like is_diff_color but treats None as DEFCOLOR (for the `color` field).
2298/// Visual comparison: Gray(0) == Rgb(0,0,0) since both are black.
2299fn is_diff_font_color(x: Option<&Color>, y: Option<&Color>) -> bool {
2300  let cx = x.unwrap_or(&DEFCOLOR);
2301  let cy = y.unwrap_or(&DEFCOLOR);
2302  if cx == cy {
2303    return false;
2304  }
2305  cx.to_rgb() != cy.to_rgb()
2306}
2307
2308/// Reference-style comparison for color field: treats None as DEFCOLOR.
2309/// Unlike is_diff_font_color, does NOT fall back to visual to_rgb() comparison.
2310/// Cmyk(0,0,0,1) IS different from Rgb(0,0,0) even though both are visually black.
2311/// This matches Perl's `ne` reference equality: two Color objects at different
2312/// addresses are "different" even if they represent the same visual color.
2313/// In our model, different Color variants = different Perl references.
2314fn is_diff_font_color_ref(x: Option<&Color>, y: Option<&Color>) -> bool {
2315  let cx = x.unwrap_or(&DEFCOLOR);
2316  let cy = y.unwrap_or(&DEFCOLOR);
2317  cx != cy
2318}
2319
2320/// Matches fonts when both are converted to toString strings.
2321/// Uses regex caching for repeated lookups.
2322/// Perl: match_font
2323pub fn match_font(font1: &str, font2: &str) -> bool {
2324  // Build a regex from font1 where '*' components become wildcards
2325  if let Some(inner) = font1
2326    .strip_prefix("Font[")
2327    .and_then(|s| s.strip_suffix(']'))
2328  {
2329    let comps: Vec<&str> = inner.split(',').collect();
2330    let re_str = format!(
2331      "^Font\\[{}\\]$",
2332      comps
2333        .iter()
2334        .map(|c| if *c == "*" {
2335          "[^,]+".to_string()
2336        } else {
2337          regex::escape(c)
2338        })
2339        .collect::<Vec<_>>()
2340        .join(",")
2341    );
2342    if let Ok(re) = Regex::new(&re_str) {
2343      return re.is_match(font2);
2344    }
2345  }
2346  false
2347}
2348
2349/// Generate XPath fragments for font matching.
2350/// Perl: font_match_xpaths
2351pub fn font_match_xpaths(font: &str) -> String {
2352  if let Some(inner) = font.strip_prefix("Font[").and_then(|s| s.strip_suffix(']')) {
2353    let comps: Vec<&str> = inner.split(',').collect();
2354    // Only check family, series, shape (indices 0, 1, 2)
2355    let mut frags: Vec<String> = Vec::new();
2356    if !comps.is_empty() && comps[0] != "*" {
2357      frags.push(format!("[{},", comps[0]));
2358    }
2359    if comps.len() > 1 && comps[1] != "*" {
2360      frags.push(format!(",{},", comps[1]));
2361    }
2362    if comps.len() > 2 && comps[2] != "*" {
2363      frags.push(format!(",{},", comps[2]));
2364    }
2365    let mut parts: Vec<String> = vec!["@_font".to_string()];
2366    for frag in frags {
2367      parts.push(format!("contains(@_font,'{frag}')"));
2368    }
2369    parts.join(" and ")
2370  } else {
2371    "@_font".to_string()
2372  }
2373}
2374
2375/// Decode a codepoint using the fontmap for a given font and/or fontencoding.
2376///
2377/// If `encoding` not provided, then lookup according to the current font's
2378/// encoding; the font family may also be used to choose the fontmap (think tt fonts!).
2379/// When `implicit` is false, we are "explicitly" asking for a decoding, such as
2380/// with \char, \mathchar, \symbol, DeclareTextSymbol and such cases.
2381/// In such cases, only codepoints specifically within the map are covered; the rest are undef.
2382/// If `implicit` is true, we'll decode token content that has made it to the stomach:
2383/// We're going to assume that SOME sort of handling of input encoding is taking place,
2384/// so that if anything above 128 comes in, it must already be Unicode!.
2385/// The lower half plane still needs to go through decoding, though, to deal
2386/// with TeX's rearrangement of ASCII...
2387/// Push a fontmap character to a string, handling known multi-char entries.
2388fn push_fontmap_char(result: &mut String, c: char, _code: u8) {
2389  // T1 position 223: "SS" (capital sharp S as two chars)
2390  if c == '\u{1E9E}' {
2391    result.push_str("SS");
2392    return;
2393  }
2394  // For standalone combining characters (Unicode Mn category), prepend NBSP as base.
2395  // Perl fontmaps encode these as UTF(0xA0)."\x{combining}" (two-char strings).
2396  if is_combining_mark(c) {
2397    result.push('\u{00A0}');
2398  }
2399  result.push(c);
2400}
2401
2402/// Check if a character is a Unicode combining mark (category Mn).
2403pub fn is_combining_mark(c: char) -> bool {
2404  matches!(c as u32,
2405    0x0300..=0x036F   // Combining Diacritical Marks
2406    | 0x1AB0..=0x1AFF // Combining Diacritical Marks Extended
2407    | 0x1DC0..=0x1DFF // Combining Diacritical Marks Supplement
2408    | 0x20D0..=0x20FF // Combining Diacritical Marks for Symbols
2409    | 0xFE20..=0xFE2F // Combining Half Marks
2410  )
2411}
2412
2413/// The glyph `\char` and a text `\chardef` print for character code `code` (Perl `FontDecode`, Package.pm:2871-2891):
2414/// up to 255 the current font's slot; above it the code point itself, as XeTeX and LuaTeX print it. The pdfTeX persona
2415/// keeps it too, with a Warning naming `cs` where pdfTeX reports "Bad character code" and prints slot 0
2416/// (tex.web:8629-8635 `scan_char_num`; ruling D-42, OXIDIZED_DESIGN_DIVERGENCES #1191). A negative code, a surrogate or
2417/// one past U+10FFFF prints nothing. `cs: None` decodes without a Warning.
2418pub fn decode_char_code(code: i64, cs: Option<&str>) -> Option<SymStr> {
2419  if let Ok(byte) = u8::try_from(code) {
2420    return decode_str(byte, None, false);
2421  }
2422  let c = u32::try_from(code).ok().and_then(char::from_u32)?;
2423  if let Some(cs) = cs
2424    && !unicode_engine_profile()
2425  {
2426    crate::Warn!(
2427      "unexpected",
2428      cs,
2429      format!(
2430        "Character code \"{code:X} ({code}) is above 255: kept as U+{code:04X} {c}, \
2431         where pdfTeX reports \"Bad character code\""
2432      )
2433    );
2434  }
2435  Some(arena::pin_char(c))
2436}
2437
2438/// Decode a codepoint, returning a SymStr that may contain multiple characters.
2439/// This handles Perl font map entries like `UTF(0xA0)."\x{0335}"` (OT1 pos 32).
2440pub fn decode_str(code: u8, encoding_opt: Option<String>, implicit: bool) -> Option<SymStr> {
2441  // First, check for multi-char overrides (for entries that can't fit in Option<char>)
2442  if let Some(s) = lookup_multichar_override(code, encoding_opt.as_deref()) {
2443    return Some(arena::pin(s));
2444  }
2445  if let Some(c) = decode(code, encoding_opt, implicit) {
2446    // T1 position 223: "SS" (capital sharp S as two chars)
2447    if c == '\u{1E9E}' {
2448      return Some(pin!("SS"));
2449    }
2450    // For standalone combining characters, prepend NBSP as base character
2451    // (Perl fontmaps encode these as UTF(0xA0)."\x{combining}")
2452    if is_combining_mark(c) {
2453      return Some(arena::pin(format!("\u{00A0}{c}")));
2454    }
2455    Some(arena::pin_char(c))
2456  } else {
2457    None
2458  }
2459}
2460
2461/// Look up multi-char override for a given encoding position.
2462/// Returns Some(String) if a multi-char override exists.
2463fn lookup_multichar_override(code: u8, encoding_opt: Option<&str>) -> Option<String> {
2464  let mut font = None;
2465  let encoding = match encoding_opt {
2466    Some(enc) if !enc.is_empty() => enc.to_string(),
2467    _ => {
2468      font = lookup_font();
2469      font
2470        .as_ref()
2471        .and_then(|f| f.get_encoding().map(|e| e.to_string()))?
2472    },
2473  };
2474  if encoding.is_empty() {
2475    return None;
2476  }
2477  // The multichar table ships in the same binding as the map array, so it is
2478  // absent until that binding is loaded. This lookup runs BEFORE `decode` —
2479  // which is what triggers the load — so without preloading here, the very
2480  // first decode for an encoding misses the table and silently falls back to
2481  // the single-char array value.
2482  //
2483  // That is not merely a lost first call: `\DeclareTextSymbol` bakes the
2484  // decoded result into a primitive body at DECLARATION time, in the preamble,
2485  // before any `\fontencoding{T2B}` has loaded the map. So T2B slot 128 was
2486  // frozen as `Ӷ` (U+04F6) instead of `Ӷ̶` (U+04F6 U+0336) — a different
2487  // letter, its stroke dropped — for the rest of the document. Perl has no
2488  // such hazard: `FontDecode` calls `LoadFontMap` first and then indexes one
2489  // map whose slot already holds the whole string.
2490  let _ = preload_font_map(&encoding);
2491  with_value_sym(decoding_map(&encoding, font.as_deref()).1, |val_opt| {
2492    if let Some(Stored::HashString(map)) = val_opt {
2493      map.get(&code.to_string()).cloned()
2494    } else {
2495      None
2496    }
2497  })
2498}
2499
2500/// The map a font decodes through, and the key of the multichar table that goes with it (Perl `FontDecode`,
2501/// Package.pm:2878-2882): its family's own map (`<encoding>_<family>_fontmap`, `OT1_typewriter`, `U_msa`), when one is
2502/// declared, with that map's multichar entries (`<encoding>_<family>_fontmap_multichar`), else its encoding's. In Perl a
2503/// map slot holds the whole string, so the family's map replaces the encoding's multichar entries too. Perl reads a
2504/// family map only after its encoding's map has loaded; here a family map stands on its own, as `font_decode`
2505/// (content.rs) already reads it: `U` has no map of its own (u_fontmap.rs), and its families' — `U_msa`, `U_msb`,
2506/// `U_eur`, and bbold's `U_blackboard` — are each one font's layout, not the encoding's (bbold_sty.rs;
2507/// OXIDIZED_DESIGN_DIVERGENCES #27).
2508fn decoding_map(encoding: &str, font: Option<&Font>) -> (Option<Fontmap>, SymStr) {
2509  // `load_font_map` preloads; keys are memoized (2026-08-23 audit R6).
2510  let map = load_font_map(encoding);
2511  if let Some(family) = font.and_then(|font| font.get_family()) {
2512    let (family_map_key, family_multichar_key) = fontmap_family_key_syms(encoding, family);
2513    let family_map: Option<Fontmap> = with_value_sym(family_map_key, |v| v.and_then(|s| s.into()));
2514    if family_map.is_some() {
2515      return (family_map, family_multichar_key);
2516    }
2517  }
2518  (map, fontmap_key_syms(encoding).multichar)
2519}
2520
2521pub fn decode(code: u8, encoding_opt: Option<String>, implicit: bool) -> Option<char> {
2522  let mut font = None;
2523  let encoding = match encoding_opt {
2524    Some(enc) => Cow::Owned(enc),
2525    None => {
2526      // Perl `FontDecode`: `$encoding = $font->getEncoding || 'OT1'`
2527      // (Package.pm L2877). The `|| 'OT1'` is NOT shared with
2528      // `FontDecodeString` (L2906), whose port is `decode_string` below and
2529      // which deliberately keeps the empty fallback — do not "align" the two.
2530      //
2531      // This branch is the one `\char` reaches (via `decode_str`, encoding
2532      // `None`). It matters in MATH mode, where `Font::math_default()` sets
2533      // `encoding: None` on purpose: without the default, the lookup ran
2534      // against the empty encoding and `$\char65$` decoded to NOTHING where
2535      // Perl gives `A`. The default lives here, rather than at the call site,
2536      // so the font stays in scope for the `<enc>_<family>_fontmap`
2537      // refinement below — resolving the encoding earlier and passing it in
2538      // would silently drop `\ttfamily`'s `OT1_typewriter` variant.
2539      font = lookup_font();
2540      if let Some(ref font) = font {
2541        match font.get_encoding() {
2542          None => Cow::Borrowed("OT1"),
2543          Some(encoding) => encoding.clone(),
2544        }
2545      } else {
2546        Cow::Borrowed("OT1")
2547      }
2548    },
2549  };
2550
2551  decode_with_map(code, &encoding, font.as_deref(), implicit)
2552}
2553
2554/// Decode a codepoint in `encoding` as `font` draws it: through the font family's own map, when one is declared
2555/// (`decoding_map`). Perl `FontDecode($n, $encoding, $font)`, as `decodeMathChar` calls it (Package.pm:2990): the
2556/// math character's encoding is the font info's, its family the font's — `\mathbb{R}` under bbold is `U` in the
2557/// `blackboard` family, decoded through `U_blackboard` (bbold_sty.rs).
2558pub fn decode_in_font(code: u8, encoding: &str, font: &Font, implicit: bool) -> Option<char> {
2559  decode_with_map(code, encoding, Some(font), implicit)
2560}
2561
2562fn decode_with_map(code: u8, encoding: &str, font: Option<&Font>, implicit: bool) -> Option<char> {
2563  let map = if encoding.is_empty() {
2564    None
2565  } else {
2566    decoding_map(encoding, font).0
2567  };
2568
2569  if implicit {
2570    if let Some(map) = map {
2571      if code < 128 {
2572        match map.get(code as usize) {
2573          None => None,
2574          Some(c) => *c,
2575        }
2576      } else {
2577        Some(code.into())
2578      }
2579    } else {
2580      Some(code.into())
2581    }
2582  } else if let Some(map) = map {
2583    match map.get(code as usize) {
2584      None => None,
2585      Some(c) => *c,
2586    }
2587  } else {
2588    None
2589  }
2590}
2591
2592pub fn decode_string(string: SymStr, encoding_opt: Option<&str>, implicit: bool) -> SymStr {
2593  let empty_sym = pin!("");
2594  if string == empty_sym {
2595    return empty_sym;
2596  }
2597  let mut font = None;
2598  let encoding = match encoding_opt {
2599    None => {
2600      font = lookup_font();
2601      if let Some(ref font) = font {
2602        font.get_encoding().unwrap_or(&Cow::Borrowed(""))
2603      } else {
2604        ""
2605      }
2606    },
2607    Some(encoding) => encoding,
2608  };
2609
2610  // Memoized key syms — this runs per digested character run, and rebuilding
2611  // the "{encoding}_fontmap"-family key strings each call was ~1M allocations
2612  // on a 1.3 s paper (2026-08-23 audit R6). `load_font_map` preloads, so no
2613  // separate `preload_font_map` call is needed.
2614  let (map, multichar_key) = if encoding.is_empty() {
2615    (None, None)
2616  } else {
2617    let (map, multichar_key) = decoding_map(encoding, font.as_deref());
2618    (map, Some(multichar_key))
2619  };
2620
2621  // Load multi-char overrides if available
2622  let multichar_map: Option<HashMap<String, String>> = if let Some(multichar_key) = multichar_key {
2623    with_value_sym(multichar_key, |val_opt| {
2624      if let Some(Stored::HashString(m)) = val_opt {
2625        Some(m.clone())
2626      } else {
2627        None
2628      }
2629    })
2630  } else {
2631    None
2632  };
2633
2634  // The decoding is spelled in a reused buffer (a String per call was one allocation per digested character, MEM1
2635  // L4a); taken out of its cell, so a nested call would only allocate its own.
2636  let mut result_string = DECODED.take();
2637  result_string.clear();
2638  let unchanged = arena::with(string, |str| {
2639    for c in str.chars() {
2640      if implicit {
2641        if let Some(ref map_ref) = map {
2642          // The whole code point is compared, so U+20041 is not slot 0x41 (Perl Package.pm:2913 `$_ < $map_max`).
2643          match u8::try_from(c) {
2644            Ok(code) if code < 128 => {
2645              // Check multi-char override first
2646              if let Some(ref mc) = multichar_map
2647                && let Some(mc_str) = mc.get(&code.to_string())
2648              {
2649                result_string.push_str(mc_str);
2650                continue;
2651              }
2652              if let Some(Some(mapc_val)) = map_ref.get(code as usize) {
2653                push_fontmap_char(&mut result_string, *mapc_val, code);
2654              }
2655            },
2656            _ => result_string.push(c),
2657          }
2658        } else {
2659          result_string.push(c)
2660        }
2661      } else if let Some(ref map_ref) = map {
2662        // A code point past the 256-slot map decodes to nothing (Perl's undef `$$map[$_]`, Package.pm:2914).
2663        let Ok(code) = u8::try_from(c) else {
2664          continue;
2665        };
2666        // Check multi-char override first
2667        if let Some(ref mc) = multichar_map
2668          && let Some(mc_str) = mc.get(&code.to_string())
2669        {
2670          result_string.push_str(mc_str);
2671          continue;
2672        }
2673        if let Some(Some(mapc_val)) = map_ref.get(code as usize) {
2674          push_fontmap_char(&mut result_string, *mapc_val, code);
2675        }
2676      }
2677    }
2678    result_string == str
2679  });
2680  let decoded = if unchanged {
2681    string
2682  } else {
2683    arena::pin(result_string.as_str())
2684  };
2685  DECODED.set(result_string);
2686  decoded
2687}
2688
2689thread_local! {
2690  /// [`decode_string`]'s buffer.
2691  static DECODED: std::cell::Cell<String> = const { std::cell::Cell::new(String::new()) };
2692}
2693
2694/// Convert stanard font size names, such as `tiny`, `Huge`, etc to f64
2695pub fn rationalize_font_size(size: &str) -> f64 {
2696  if let Some(symbolic) = FONT_SIZE.get(size) {
2697    *symbolic * defsize()
2698  } else {
2699    // Perl: return $size — if not a symbolic name, return the numeric value as-is
2700    size.parse::<f64>().unwrap_or_else(|_| defsize())
2701  }
2702}
2703
2704/// convert size to percent
2705pub fn relative_font_size(newsize: f64, oldsize: f64) -> String {
2706  s!("{}%", (0.5 + 100.0 * newsize / oldsize).floor())
2707}
2708
2709/// A horizontal List with a width is a finished paragraph (`repack_horizontal`), which a text
2710/// group holding a `\par` carries into the line it sits in (a tikz `align=center` node's `\\`
2711/// lines, a `{\footnotesize …\par …}` block): measured as one unit on lines of its own — neither
2712/// opened into the words around it nor run into them (Perl's flat text groups never nest one,
2713/// Font.pm:731-746). Witnesses 2605.28170 (a prompt box: 486pt, pdflatex 570, run into one line
2714/// 233), 2605.15377, 2605.01547 (a figure 392.53pt wide as pdflatex; 718.6 before 58b).
2715fn is_finished_paragraph(bx: &Digested) -> bool {
2716  matches!(bx.data(), DigestedData::List(_))
2717    && bx.has_property("width")
2718    && bx
2719      .get_property("mode")
2720      .is_some_and(|mode| mode.to_string() == "horizontal")
2721}
2722
2723#[cfg(test)]
2724mod tests {
2725  use super::*;
2726
2727  #[test]
2728  fn relative_font_size_same_is_100() {
2729    assert_eq!(relative_font_size(10.0, 10.0), "100%");
2730    assert_eq!(relative_font_size(12.0, 12.0), "100%");
2731  }
2732
2733  #[test]
2734  fn relative_font_size_doubled_is_200() {
2735    assert_eq!(relative_font_size(20.0, 10.0), "200%");
2736  }
2737
2738  #[test]
2739  fn relative_font_size_half_is_50() {
2740    assert_eq!(relative_font_size(5.0, 10.0), "50%");
2741  }
2742
2743  /// #542: NOMINAL_FONT_SIZE is a float, not an integer — the `11pt` class option
2744  /// is `10.95` (LaTeX's `\@xipt`), which the reader must not truncate. Perl
2745  /// `DEFSIZE` reads `lookupValue('NOMINAL_FONT_SIZE')` directly as a float
2746  /// (`Common/Font.pm:44`); the Rust reader used to go through `lookup_int`.
2747  #[test]
2748  fn defsize_preserves_fractional_nominal_font_size() {
2749    use crate::{
2750      common::float::Float,
2751      state::{State, StateOptions, assign_value, set_state},
2752    };
2753    set_state(State::new(StateOptions::default()));
2754    // Unset → default 10.
2755    assert_eq!(defsize(), 10.0, "defsize defaults to 10 when unset");
2756    // 11pt → 10.95, the fractional value the old lookup_int truncated to 10.
2757    assign_value("NOMINAL_FONT_SIZE", Float(10.95), None);
2758    assert_eq!(
2759      defsize(),
2760      10.95,
2761      "defsize preserves the fractional 11pt size"
2762    );
2763    // An integral float still reads back cleanly.
2764    assign_value("NOMINAL_FONT_SIZE", Float(12.0), None);
2765    assert_eq!(defsize(), 12.0, "12pt reads back as 12.0");
2766  }
2767
2768  /// #638: LaTeXML treats the font `encoding` three different ways, and this
2769  /// pins all three so the "omit encoding from `relative_to`" fix cannot drift
2770  /// into collapsing font *identity*. Two fonts that differ ONLY in encoding are:
2771  ///   - **unequal** (`eq`) and **distinctly hashable** — a T1 span is a
2772  ///     different font than an OT1 span, so `set_node_font`'s `_font` /
2773  ///     `node_fonts` keys keep them apart;
2774  ///   - **distance 0** — encoding alone never opens a font wrapper (Perl's
2775  ///     `distance` skips it explicitly, `Common/Font.pm`);
2776  ///   - **empty under `relative_to`** — encoding is a FontMap-lookup key consumed
2777  ///     at digestion, meaningless as output, so it is omitted from the relativized
2778  ///     attribute set (otherwise it leaks onto raw `xhtml:*`, whose `attribute *`
2779  ///     schema wildcard accepts it — the reported bug).
2780  #[test]
2781  fn encoding_is_font_identity_but_not_distance_or_output() {
2782    use crate::state::{State, StateOptions, set_state};
2783    set_state(State::new(StateOptions::default()));
2784
2785    let base = Font::default();
2786    let mut t1 = base.clone();
2787    t1.encoding = Some(Cow::Borrowed("T1"));
2788    let mut ot1 = base.clone();
2789    ot1.encoding = Some(Cow::Borrowed("OT1"));
2790
2791    // Identity: different encodings ⇒ different fonts.
2792    assert_ne!(
2793      t1, ot1,
2794      "fonts differing only in encoding must not be equal"
2795    );
2796    assert_ne!(
2797      t1.to_hashable(),
2798      ot1.to_hashable(),
2799      "differently-encoded fonts must get distinct `_font` ids"
2800    );
2801
2802    // Distance: encoding is not a font-switch factor (faithful to Perl).
2803    assert_eq!(
2804      t1.distance(&ot1),
2805      0,
2806      "encoding alone must not count as a font-switch distance"
2807    );
2808
2809    // Output: encoding is never emitted as a relativized attribute (#638). Since
2810    // the two fonts differ only in encoding, the relativized set is empty.
2811    let rel = t1.relative_to(&ot1);
2812    assert!(
2813      rel.is_empty(),
2814      "relative_to must not emit @encoding (it leaks onto foreign xhtml); got {rel:?}"
2815    );
2816  }
2817
2818  #[test]
2819  fn match_font_exact_wildcard_tail() {
2820    // Font[family,series,shape,size,...] — '*' matches any single
2821    // component.
2822    // match_font(f1, f2) returns true iff f2 matches the pattern f1.
2823    // f1 with all-wildcards should match any well-formed Font[...].
2824    assert!(match_font("Font[*,*,*,*]", "Font[rm,med,up,10]"));
2825  }
2826
2827  #[test]
2828  fn match_font_exact_match() {
2829    assert!(match_font("Font[rm,med,up,10]", "Font[rm,med,up,10]"));
2830    assert!(!match_font("Font[rm,med,up,10]", "Font[sf,med,up,10]"));
2831  }
2832
2833  #[test]
2834  fn match_font_partial_wildcard() {
2835    // First position wildcard matches rm, sf, tt, etc.
2836    assert!(match_font("Font[*,med,up,10]", "Font[rm,med,up,10]"));
2837    assert!(match_font("Font[*,med,up,10]", "Font[sf,med,up,10]"));
2838    // But a non-wildcard in series must match.
2839    assert!(!match_font("Font[*,bold,up,10]", "Font[rm,med,up,10]"));
2840  }
2841
2842  #[test]
2843  fn match_font_malformed_input() {
2844    // Missing Font[...] wrapper → false.
2845    assert!(!match_font("not_a_font", "Font[rm,med,up,10]"));
2846  }
2847
2848  #[test]
2849  fn font_match_xpaths_all_wildcards_is_attr_only() {
2850    let xp = font_match_xpaths("Font[*,*,*,*]");
2851    // All wildcards → just @_font, no contains(...) fragments.
2852    assert_eq!(xp, "@_font");
2853  }
2854
2855  #[test]
2856  fn font_match_xpaths_includes_specified_components() {
2857    let xp = font_match_xpaths("Font[rm,bold,*,*]");
2858    // Family and series specified; shape/size wildcarded.
2859    assert!(xp.contains("@_font"));
2860    assert!(xp.contains("contains"));
2861    assert!(xp.contains("rm"));
2862    assert!(xp.contains("bold"));
2863  }
2864
2865  #[test]
2866  fn font_match_xpaths_malformed_is_empty_or_fallback() {
2867    let xp = font_match_xpaths("garbage");
2868    // Not a Font[...] format → some minimal/fallback output.
2869    // Implementation detail: we don't over-constrain, just verify
2870    // it doesn't panic.
2871    let _ = xp;
2872  }
2873}