use super::{BoxNode, GlueSign, GlueSource, LeaderKind, Node, Scaled};
use crate::dimen::{print_scaled, UNITY};
use crate::math::noad::{Class, Delimiter, Field, Limits, MathChar, Noad, Style};
pub trait FontIds {
fn font_id_text(&self, f: usize) -> String;
}
pub struct Numbered;
impl FontIds for Numbered {
fn font_id_text(&self, f: usize) -> String {
format!("FONT{f}")
}
}
pub struct Display<'a> {
pub depth: i64,
pub breadth: i64,
pub esc: &'a str,
pub fonts: &'a dyn FontIds,
}
fn print_ascii(out: &mut String, c: char) {
let code = u32::from(c);
if code < 32 {
out.push_str("^^");
out.push(char::from(code as u8 + 64));
} else if code == 127 {
out.push_str("^^?");
} else {
out.push(c);
}
}
fn print_glue(out: &mut String, d: Scaled, order: crate::glue::Order, s: &str) {
out.push_str(&print_scaled(d));
match order {
o if !(0..=3).contains(&o) => out.push_str("foul"),
0 => out.push_str(s),
o => {
out.push_str("fil");
for _ in 1..o {
out.push('l');
}
}
}
}
pub fn print_spec(out: &mut String, g: &crate::glue::Glue, s: &str) {
out.push_str(&print_scaled(g.natural));
out.push_str(s);
if g.stretch != 0 {
out.push_str(" plus ");
print_glue(out, g.stretch, g.stretch_order, s);
}
if g.shrink != 0 {
out.push_str(" minus ");
print_glue(out, g.shrink, g.shrink_order, s);
}
}
fn print_rule_dimen(out: &mut String, d: Scaled) {
match d == super::NULL_FLAG {
true => out.push('*'),
false => out.push_str(&print_scaled(d)),
}
}
fn skip_param_name(code: usize) -> &'static str {
crate::params::GLUE_NAMES
.get(code)
.copied()
.unwrap_or("[unknown glue parameter!]")
}
impl Display<'_> {
fn esc(&self, out: &mut String, name: &str) {
out.push_str(self.esc);
out.push_str(name);
}
fn font_and_char(&self, out: &mut String, font: usize, c: char) {
self.esc(out, &self.fonts.font_id_text(font));
out.push(' ');
print_ascii(out, c);
}
pub fn show_box(&self, list: &[Node]) -> String {
let breadth = match self.breadth <= 0 {
true => 5,
false => self.breadth,
};
let mut out = String::new();
let mut history = String::new();
self.show_node_list(&mut out, list, &mut history, breadth);
out.push('\n');
out
}
fn show_node_list(&self, out: &mut String, list: &[Node], history: &mut String, breadth: i64) {
if history.len() as i64 > self.depth {
if !list.is_empty() {
out.push_str(" []");
}
return;
}
let mut n = 0i64;
let mut i = 0usize;
while i < list.len() {
out.push('\n');
out.push_str(history);
n += 1;
if n > breadth {
out.push_str("etc.");
return;
}
self.display_node(out, &list[i], history, breadth);
i += 1;
}
}
fn nested(&self, out: &mut String, list: &[Node], history: &mut String, breadth: i64) {
history.push('.');
self.show_node_list(out, list, history, breadth);
history.pop();
}
fn display_node(&self, out: &mut String, p: &Node, history: &mut String, breadth: i64) {
match p {
Node::Char(c) => self.font_and_char(out, c.font, c.character),
Node::Box(b) => {
self.display_box(out, b);
self.nested(out, &b.list, history, breadth);
}
Node::Rule(r) => {
self.esc(out, "rule(");
print_rule_dimen(out, r.height);
out.push('+');
print_rule_dimen(out, r.depth);
out.push_str(")x");
print_rule_dimen(out, r.width);
}
Node::Ins(ins) => {
self.esc(out, "insert");
out.push_str(&ins.number.to_string());
out.push_str(", natural size ");
out.push_str(&print_scaled(ins.height));
out.push_str("; split(");
print_spec(out, &ins.split_top_skip, "");
out.push(',');
out.push_str(&print_scaled(ins.depth));
out.push_str("); float cost ");
out.push_str(&ins.float_cost.to_string());
self.nested(out, &ins.list, history, breadth);
}
Node::Whatsit(text) => {
self.esc(out, "special");
out.push('{');
out.push_str(text);
out.push('}');
}
Node::Out(w) => self.esc(out, &w.display),
Node::Glue(g) if g.kind.is_leaders() => {
self.esc(out, "");
match g.kind {
LeaderKind::Centred => out.push('c'),
LeaderKind::Expanded => out.push('x'),
_ => {}
}
out.push_str("leaders ");
print_spec(out, &g.spec, "");
if let Some(leader) = &g.leader {
self.nested(out, std::slice::from_ref(leader), history, breadth);
}
}
Node::Glue(g) => {
self.esc(out, "glue");
if g.source != GlueSource::Normal {
out.push('(');
match g.source {
GlueSource::CondMath => self.esc(out, "nonscript"),
GlueSource::MuGlue => self.esc(out, "mskip"),
other => self.esc(out, skip_param_name(other.param_code().unwrap_or(99))),
}
out.push(')');
}
if g.source != GlueSource::CondMath {
out.push(' ');
match g.source {
GlueSource::MuGlue => print_spec(out, &g.spec, "mu"),
_ => print_spec(out, &g.spec, ""),
}
}
}
Node::Kern { width, explicit } => {
self.esc(out, "kern");
if *explicit {
out.push(' ');
}
out.push_str(&print_scaled(*width));
}
Node::AccKern(width) => {
self.esc(out, "kern");
out.push(' ');
out.push_str(&print_scaled(*width));
out.push_str(" (for accent)");
}
Node::Math(width) | Node::MathOff(width) => {
let side = match p {
Node::Math(_) => "mathon",
_ => "mathoff",
};
self.esc(out, side);
if *width != 0 {
out.push_str(", surrounded ");
out.push_str(&print_scaled(*width));
}
}
Node::Ligature(c, lig) => {
self.font_and_char(out, c.font, c.character);
out.push_str(" (ligature ");
if lig.left_boundary {
out.push('|');
}
for &k in &lig.components {
print_ascii(out, k);
}
if lig.right_boundary {
out.push('|');
}
out.push(')');
}
Node::Penalty(v) => {
self.esc(out, "penalty ");
out.push_str(&v.to_string());
}
Node::Disc(d) => {
self.esc(out, "discretionary");
if d.replace_count > 0 {
out.push_str(" replacing ");
out.push_str(&d.replace_count.to_string());
}
self.nested(out, &d.pre_break, history, breadth);
history.push('|');
self.show_node_list(out, &d.post_break, history, breadth);
history.pop();
}
Node::Mark(text) => {
self.esc(out, "mark");
out.push('{');
out.push_str(text);
out.push('}');
}
Node::Adjust(list) => {
self.esc(out, "vadjust");
self.nested(out, list, history, breadth);
}
}
}
fn display_box(&self, out: &mut String, b: &BoxNode) {
self.esc(out, if b.vertical { "v" } else { "h" });
out.push_str("box(");
out.push_str(&print_scaled(b.height));
out.push('+');
out.push_str(&print_scaled(b.depth));
out.push_str(")x");
out.push_str(&print_scaled(b.width));
let g = b.glue_set;
if g != 0.0 && b.glue_sign != GlueSign::Normal {
out.push_str(", glue set ");
if b.glue_sign == GlueSign::Shrinking {
out.push_str("- ");
}
if g.abs() > 20000.0 {
match g > 0.0 {
true => out.push('>'),
false => out.push_str("< -"),
}
print_glue(out, 20000 * UNITY, b.glue_order, "");
} else {
print_glue(out, (UNITY as f64 * g).round() as Scaled, b.glue_order, "");
}
}
if b.shift_amount != 0 {
out.push_str(", shifted ");
out.push_str(&print_scaled(b.shift_amount));
}
}
pub fn short_display(&self, out: &mut String, list: &[Node], font: &mut Option<usize>) {
let mut i = 0usize;
while i < list.len() {
match &list[i] {
Node::Char(c) => {
if *font != Some(c.font) {
self.esc(out, &self.fonts.font_id_text(c.font));
out.push(' ');
*font = Some(c.font);
}
print_ascii(out, c.character);
}
Node::Box(_)
| Node::Ins(_)
| Node::Whatsit(_)
| Node::Out(_)
| Node::Mark(_)
| Node::Adjust(_) => out.push_str("[]"),
Node::Rule(_) => out.push('|'),
Node::Glue(g) if g.spec != crate::glue::Glue::default() => out.push(' '),
Node::Math(_) | Node::MathOff(_) => out.push('$'),
Node::Ligature(c, lig) => {
if *font != Some(c.font) {
self.esc(out, &self.fonts.font_id_text(c.font));
out.push(' ');
*font = Some(c.font);
}
for &k in &lig.components {
print_ascii(out, k);
}
}
Node::Disc(d) => {
self.short_display(out, &d.pre_break, font);
self.short_display(out, &d.post_break, font);
i += d.replace_count;
}
_ => {}
}
i += 1;
}
}
}
impl Display<'_> {
pub fn show_mlist_from(&self, out: &mut String, list: &[Noad], history: &mut String) {
let breadth = match self.breadth <= 0 {
true => 5,
false => self.breadth,
};
self.show_noad_list(out, list, history, breadth);
}
fn show_noad_list(&self, out: &mut String, list: &[Noad], history: &mut String, breadth: i64) {
if history.len() as i64 > self.depth {
if !list.is_empty() {
out.push_str(" []");
}
return;
}
for (n, q) in list.iter().enumerate() {
out.push('\n');
out.push_str(history);
if n as i64 >= breadth {
out.push_str("etc.");
return;
}
self.display_noad(out, q, history, breadth);
}
}
fn fam_and_char(&self, out: &mut String, c: &MathChar) {
self.esc(out, "fam");
out.push_str(&c.fam.to_string());
out.push(' ');
print_ascii(out, char::from(c.character));
}
fn delimiter(&self, out: &mut String, d: &Delimiter) {
let a = ((d.small_fam * 256 + usize::from(d.small_char)) * 0x1000)
+ d.large_fam * 256
+ usize::from(d.large_char);
out.push_str(&format!("\"{a:X}"));
}
fn subsidiary(&self, out: &mut String, f: &Field, c: char, history: &mut String, breadth: i64) {
if history.len() as i64 >= self.depth {
if !f.is_empty() {
out.push_str(" []");
}
return;
}
history.push(c);
match f {
Field::Char(m) => {
out.push('\n');
out.push_str(history);
self.fam_and_char(out, m);
}
Field::Box(b) => {
self.show_node_list(
out,
std::slice::from_ref(&Node::Box(b.as_ref().clone())),
history,
breadth,
);
}
Field::List(l) if l.is_empty() => {
out.push('\n');
out.push_str(history);
out.push_str("{}");
}
Field::List(l) => self.show_noad_list(out, l, history, breadth),
Field::Literal(ch) => {
out.push('\n');
out.push_str(history);
print_ascii(out, *ch);
}
Field::Empty => {}
}
history.pop();
}
fn style(&self, out: &mut String, s: Style) {
match s / 2 {
0 => self.esc(out, "displaystyle"),
1 => self.esc(out, "textstyle"),
2 => self.esc(out, "scriptstyle"),
3 => self.esc(out, "scriptscriptstyle"),
_ => out.push_str("Unknown style!"),
}
}
fn display_noad(&self, out: &mut String, q: &Noad, history: &mut String, breadth: i64) {
let atom = match q {
Noad::Style(s) => return self.style(out, *s),
Noad::Choice(c) => {
self.esc(out, "mathchoice");
for (ch, l) in [
('D', &c.display),
('T', &c.text),
('S', &c.script),
('s', &c.script_script),
] {
history.push(ch);
self.show_noad_list(out, l, history, breadth);
history.pop();
}
return;
}
Noad::Fraction(f) => {
self.esc(out, "fraction, thickness ");
match f.thickness {
None => out.push_str("= default"),
Some(t) => out.push_str(&print_scaled(t)),
}
if !f.left_delimiter.is_null() {
out.push_str(", left-delimiter ");
self.delimiter(out, &f.left_delimiter);
}
if !f.right_delimiter.is_null() {
out.push_str(", right-delimiter ");
self.delimiter(out, &f.right_delimiter);
}
self.subsidiary(
out,
&Field::List(f.numerator.clone()),
'\\',
history,
breadth,
);
self.subsidiary(
out,
&Field::List(f.denominator.clone()),
'/',
history,
breadth,
);
return;
}
Noad::Left(d) | Noad::Right(d) => {
let name = match q {
Noad::Left(_) => "left",
_ => "right",
};
self.esc(out, name);
self.delimiter(out, d);
return;
}
Noad::Node(n) => return self.display_node(out, n, history, breadth),
Noad::Glue(w) | Noad::Kern(w) => {
self.esc(out, "kern");
out.push_str(&print_scaled(*w));
return;
}
Noad::MuKern(w) => {
self.esc(out, "mkern");
out.push_str(&print_scaled(*w));
out.push_str("mu");
return;
}
Noad::MuGlue(g) => {
self.esc(out, "glue(");
self.esc(out, "mskip");
out.push_str(") ");
out.push_str(&print_scaled(g.natural));
out.push_str("mu");
return;
}
Noad::Atom(a) => {
let name = match a.class() {
Class::Ord => "mathord",
Class::Op => "mathop",
Class::Bin => "mathbin",
Class::Rel => "mathrel",
Class::Open => "mathopen",
Class::Close => "mathclose",
Class::Punct => "mathpunct",
Class::Inner => "mathinner",
};
self.esc(out, name);
a
}
Noad::Over(a) => {
self.esc(out, "overline");
a
}
Noad::Under(a) => {
self.esc(out, "underline");
a
}
Noad::VCenter(a) => {
self.esc(out, "vcenter");
a
}
Noad::Radical(r) => {
self.esc(out, "radical");
self.delimiter(out, &r.left_delimiter);
&r.nucleus
}
Noad::Accent(acc) => {
self.esc(out, "accent");
self.fam_and_char(out, &acc.accent);
&acc.atom
}
};
match atom.limits {
Limits::Normal => {}
Limits::Above => self.esc(out, "limits"),
Limits::Beside => self.esc(out, "nolimits"),
}
self.subsidiary(out, &atom.nucleus, '.', history, breadth);
self.subsidiary(out, &atom.supscr, '^', history, breadth);
self.subsidiary(out, &atom.subscr, '_', history, breadth);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::glue::Glue;
use crate::node::{CharNode, GlueNode, RuleNode};
struct Tenrm;
impl FontIds for Tenrm {
fn font_id_text(&self, _f: usize) -> String {
"tenrm".to_string()
}
}
fn display() -> Display<'static> {
Display {
depth: 2147483647,
breadth: 2147483647,
esc: "\\",
fonts: &Tenrm,
}
}
fn ch(c: char, width: Scaled) -> Node {
Node::Char(CharNode {
font: 1,
character: c,
width,
height: 0,
depth: 0,
})
}
#[test]
fn an_hbox_of_three_letters_reads_as_tex_logs_it() {
let b = BoxNode {
width: 1001247,
height: 455111,
list: vec![
ch('a', 327681),
ch('b', 364090),
Node::Kern {
width: 18205,
explicit: false,
},
ch('c', 291268),
],
..BoxNode::null()
};
assert_eq!(
display().show_box(&[Node::Box(b)]),
"\n\\hbox(6.94444+0.0)x15.27782\n.\\tenrm a\n.\\tenrm b\n.\\kern0.27779\n.\\tenrm c\n"
);
}
#[test]
fn glue_kerns_and_rules_follow_sections_187_to_191() {
let list = vec![
Node::Glue(GlueNode::param(
Glue {
natural: 12 * UNITY,
stretch: UNITY,
stretch_order: 1,
..Glue::default()
},
GlueSource::BaselineSkip,
)),
Node::Kern {
width: 2 * UNITY,
explicit: true,
},
Node::Rule(RuleNode {
width: super::super::NULL_FLAG,
height: 26214,
depth: 0,
}),
Node::Penalty(-10000),
];
assert_eq!(
display().show_box(&list),
"\n\\glue(\\baselineskip) 12.0 plus 1.0fil\n\\kern 2.0\n\\rule(0.4+0.0)x*\n\\penalty -10000\n"
);
}
#[test]
fn breadth_and_depth_cut_the_display_off() {
let inner = BoxNode {
list: vec![ch('x', 0)],
..BoxNode::null()
};
let d = Display {
depth: 0,
breadth: 1,
..display()
};
assert_eq!(
d.show_box(&[Node::Box(inner.clone()), ch('y', 0)]),
"\n\\hbox(0.0+0.0)x0.0 []\netc.\n"
);
}
#[test]
fn glue_set_is_printed_with_its_order() {
let b = BoxNode {
glue_set: 0.5,
glue_sign: GlueSign::Stretching,
glue_order: 1,
..BoxNode::null()
};
assert_eq!(
display().show_box(&[Node::Box(b)]),
"\n\\hbox(0.0+0.0)x0.0, glue set 0.5fil\n"
);
}
#[test]
fn a_ligature_shows_its_components() {
let fi = Node::Ligature(
CharNode {
font: 1,
character: '\u{c}',
width: 0,
height: 0,
depth: 0,
},
crate::node::Ligature {
components: vec!['f', 'i'],
..Default::default()
},
);
assert_eq!(display().show_box(&[fi]), "\n\\tenrm ^^L (ligature fi)\n");
}
#[test]
fn short_display_names_the_font_once() {
let mut out = String::new();
let mut font = None;
display().short_display(
&mut out,
&[
ch('a', 0),
Node::Glue(GlueNode::new(Glue::fixed(UNITY))),
ch('b', 0),
Node::Rule(RuleNode::running()),
],
&mut font,
);
assert_eq!(out, "\\tenrm a b|");
}
}